我有这段代码与 React 一起工作,它变得非常困惑,所以我想知道是否有办法让这段代码和其他非常相似的代码看起来更干净。
render() {
let result = null;
var obj = this.state.welcome;
let test = null;
if (this.state.isReal) {
test = Object.entries(obj).map(([key, value], index) => {
return (
<li key={index}>
Word: "{key}" repeats: {value} times
</li>
);
});
result = (
<Aux>
<h3>Title</h3>
<ul>{test}</ul>
</Aux>
);
}
return (
<Aux>
<div className="bframe">
<div className="form" />
{result}
</div>
<Footer />
</Aux>
);
}
我想知道是否可以在“return”语句之前移动所有内容,最好放在单独的文件中。我尝试制作一个功能组件并传递 Prop ,但我无法在那里做循环。有什么建议吗?
最佳答案
您可以将代码缩减为以下内容:
render() {
const { welcome, isReal } = this.state
return (
<Aux>
<div className="bframe">
<div className="form" />
{isReal &&
<Aux>
<h3>Title</h3>
<ul>
{Object.entries(welcome).map(([key, value]) =>
<li key={key}>
Word: "{key}" repeats: {value} times
</li>
)}
</ul>
</Aux>
}
</div>
<Footer />
</Aux>
);
}
不要使用 var
, 默认使用 const
如果你想修改你的变量,使用 let
.
您可以使用内联 if
选择是否呈现元素。 : &&
.
你的函数也是不必要的,因为它可以被内联 JS 替换。
你的 map
也可以减少:x.map(a => { return <div/> }
至 x.map(a => <div/>
.
您还可以使用 key
每个项目作为 React key
因为无论如何它们在您的对象中都必须是唯一的。
关于javascript - 使用循环和 map 时更干净的 react 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420673/