在我的组件中,我有一个如下所示的状态:
class MainClass
constructor(props) {
super(props);
this.state = {
form: {
startDate:"1/11/2020",
endDate:"5/11/2020",
....
},
};
}
我有一个更新开始和结束日期的函数,还有一个更新表单的函数
handleFormChanges = targets => {
targets.forEach(function (target) {
this.setState({
form: { ...this.state.form, [target.name]: target.value },
});
});
};
.....
updateDate(startDate, endDate) {
const newStartDate = {name:"startDate", value:startDate.value}
const newEndDate = {name:"endDate", value:endDate.value}
this.handleFormChanges([newStartDate, newEndDate])
}
所以我意识到在循环中调用setState是一种代码气味,而不是react是如何工作的。如何组合目标数组,以便只需调用setState一次?
发布于 2020-08-14 17:42:10
您可以使用reduce
一次性累积targets
编辑:要同时处理单个对象和对象数组,可以用方括号[]
包装targets
,然后用flat()
包装
this.setState({
form: {
...this.state.form,
...[targets].flat().reduce(
(acc, target) => ({ ...acc, [target.name]: target.value }),
{}
),
},
})
发布于 2020-08-14 17:41:52
你可以拥有像这样的东西
const newObj={};
targets.forEach(function (target) {
newObj[target.name]=target.value,
});
this.setState({...this.state.form,...newObj})
发布于 2020-08-14 17:46:57
这绝对是一个错误的想法,因为你可能会错过一些数据,并在每次迭代中导致额外的渲染。
主要思想是每个函数使用一次setState。此外,您也不需要使用handleFormChanges,更好的做法是按键添加值)
updateDate(startDate, endDate) {
this.setState({
form: {
...this.state.form,
"startDate": startDate.value,
endDate: endDate.value
},
});
}
https://stackoverflow.com/questions/63417566
复制相似问题