以下代码输出两个单独的表单部分。一切正常,但我有两个相似的 for() 循环和两个也相似的 map() 函数。我想学习如何使用 for() 循环和 map() 函数编写嵌套脚本,以便我可以向我的 state.program 对象添加更多属性,并且我的表单将自动更新,而无需添加另一个 for() 或 map ()。
基本上,我试图循环对象,创建数组来映射到我的组件 Prop 。我的想法是错误的吗?
我希望我的问题的描述有意义。这是 React 组件...
class CreateProgram extends Component {
state = {
program: {
description: {
title: {
label: 'Program title',
value: ''
},
category: {
label: 'Program category',
value: ''
}
},
location: {
location_title: {
label: 'location title',
value: ''
},
location_coor: {
label: 'location coordinates',
value: null
}
}
}
};
render() {
return <Program items={this.state.program} />;
}
}
export default CreateProgram;
class Program extends Component {
render() {
const { items } = this.props;
const descriptionArray = [];
const locationArray = [];
for (let key in items.description) {
descriptionArray.push({
id: key,
value: items.description[key]
});
}
for (let key in items.location) {
locationArray.push({
id: key,
value: items.location[key]
});
}
return (
<>
<div className="form-section">
{descriptionArray.map(element => (
<Input
label={element.value.label}
value={element.value.value}
changed={event =>
changed(event, element.id, 'program', 'description')
}
/>
))}
</div>
<div className="form-section">
{locationArray.map(element => (
<Input
label={element.value.label}
value={element.value.value}
changed={event =>
changed(event, element.id, 'program', 'location')
}
/>
))}
</div>
</>
);
}
}
export default Program;
最佳答案
您可以简化父状态:
state = {
description: {
title: {
label: "Program title",
value: ""
},
category: {
label: "Program category",
value: ""
}
},
location: {
location_title: {
label: "location title",
value: ""
},
location_coor: {
label: "location coordinates",
value: null
}
}
};
然后将它们分别传递给子组件:
render() {
return (
<Program
description={this.state.description}
location={this.state.location}
/>
);
};
并在子组件中使用Object.entries返回数组来映射每个元素:
Object.entries(this.props.description).map(([key, value]) => (
<Input
key={key}
label={value.label}
value={value.value}
changed={event => changed(event, key, "program", "description")}
/>
));
Object.entries(this.props.location).map(([key, value]) => (
<Input
key={key}
label={value.label}
value={value.value}
changed={event => changed(event, key, "program", "location")}
/>
));
关于javascript - 如何在JSX中编写嵌套循环以减少重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468692/