【发布时间】:2019-08-27 21:44:10
【问题描述】:
我目前在 react native 中有一个函数,它执行以下操作:
resetThenSet = (id, arrayId, title) => {
if(arrayId != 'selectProduct') {
// Setting state for each selected dropdown in selectedDropdowns
this.setState({
dataShowingToggle: true,
selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
}, this.getProductCost(arrayId, id)
);
}
我运行上面的程序,我可以确认 arrayId 和 title 变量是有效的并且包含数据。 arrayId 也不是“selectProduct”。我在调试时在其中添加了一个 console.log 以确保它运行,确实如此。我期望的预期行为是状态会立即更新。
但是 selectedDropdowns 的状态没有更新。当我添加: console.log(this.state) this.setState 更新后没有变化。如果我运行该函数两次,它将在第二次运行时更新。
为了进一步测试,我添加了如下静态输入:
this.setState({
dataShowingToggle: true,
selectedDropdowns: {...this.state.selectedDropdowns, testField: 'me here'}
}, this.getProductCost(arrayId, id)
);
console.log(this.state);
它只在第一次运行后更新状态。我错过了什么吗?
更新: 我更新了代码以在回调 setstate 时运行 console.log:
if(arrayId != 'selectProduct') {
// Setting state for each selected dropdown in selectedDropdowns
console.log(arrayId + title);
console.log('i run');
this.setState({
dataShowingToggle: true,
selectedDropdowns: {...this.state.selectedDropdowns, [arrayId]: title}
}, console.log(this.state)
);
};
console.log 是 arrayId + 标题的“quantityProduct 25” console.log(我运行) 然后这个状态不显示quantityProduct 25
【问题讨论】:
-
this.getProductCost是做什么的?当您的状态突变“请求”完成时,该函数将被调用。
标签: javascript reactjs