尝试删除冗余代码但无法解决问题,任何帮助都会有所帮助



以下代码创建了一个功能组件,其中包含多个对象数组,我想在UI中显示这些数组,我重复了很多代码,我想使其干净并删除任何冗余代码。代码工作正常,但唯一的问题是重构代码并删除冗余部分。

function About() {
const title = "we are a team";
// leadership array.
const leadership = [
{
name: "abc",
department: "abc",
phone: "abc",
email: "abc",
},
{
name: "abc",
department: "abc",
phone: "abc",
email: "abc",
},
];

// business array
const business = [
{
name: "abc",
department: "abc",
email: "abc",
},
{
name: "abc",
department: "abc",
email: "abc",
},
];

// mapping through the leadership array and displaying the content in the UI
const row1 = leadership.map((row) => (
<div className="column">
<div className="card">
<div className="container">
<h2>{row.name}</h2>
<p>{row.department}</p>
<p>{row.phone}</p>
<p>{row.email}</p>
</div>
</div>
</div>
));

// mapping through the leadership array and displaying the content in the UI
const row2 = business.map((row) => (
<div className="column">
<div className="card">
<div className="container">
<h2>{row.name}</h2>
<p>{row.department}</p>
<p>{row.email}</p>
</div>
</div>
</div>
));

// returning the content and rendering it in the UI
return (
<div className="home-component">
<div className="home-content">
<h1 style={stylesheader}> Meet the team </h1>
<h2 style={stylehead}>{title}</h2>
<h2 style={styles}> Leadership </h2>
<div className="row" style={style1}>
{row1}
</div>
<h2 style={styles}> Business Development </h2>
<div className="row" style={style1}>
{row2}
</div>
</div>
</div>
);
}
export default About;

您希望尽可能避免重复,因此在您的代码中,我会将每个<h2>块移动到一个简单的函数中,例如:

h2Renderer(title, rowData) {
return (
<div>
<h2 style={styles}>{ title }</h2>
<div className="row" style={style1}>
{
rowData.map((row, index) => {
return (
<div key={ `h2row-${index}` } className="column">
<div className="card"> 
<div className="container">
<h2>{row.name}</h2>
<p>{row.department}</p>
{ row.phone ? <p>{row.phone}</p> : null }
<p>{row.email}</p>
</div>
</div>
</div>
);
});
}
</div>
</div>
);
}

由于"phone"似乎是可选的,因此"三元表达式"'{ row.phone ? <p>{row.phone}</p> : null }'如果它是行对象的属性,它将添加"phone"。

在渲染函数 'return' 语句中为每组行调用这个 h2Renderer((,并传入标题:

return (
<div className="home-component">
<div className="home-header">
<Header/>
</div>
<div className="home-content" >
<h1 style={stylesheader}> Meet the team </h1>
<h2 style={stylehead}>{title}</h2>
{ this.h2Renderer(" Leadership ", row1 ) }
{ this.h2Renderer(" Business Development ", row2 ) }
{ this.h2Renderer(" Algorithm Development ", row3 ) }
{ this.h2Renderer(" Software Development ", row4 ) }
</div>
<Footer/>
</div>
);
}

稍后,我相信您可以通过将数据数组和"title"标头作为组件的 props 传递来减少代码行数,并在 h2Renderer 中使用 props 而不是传递参数。

相关内容

最新更新