【发布时间】:2021-06-09 18:34:42
【问题描述】:
我有一个功能,当我按下按钮时,我会接收数据[对象数组]。我遍历这个数组以找到其中一个对象以将其存储在状态中。
当我第一次单击按钮时,控制台日志显示状态未更新,但当我再次单击时,它显示状态已更新:
constructor(props) {
super(props);
this.state = {
listOfItems: [],
isOpen: false,
modal: null,
}
}
findKey(key) {
console.log(key);
console.log(this.state.listOfItems);
let foo;
for (var i in this.state.listOfItems) {
if (this.state.listOfItems[i].id == key) {
foo = this.state.listOfItems[i];
this.setState({ modal: foo });
}
}
// the first time i call the func it returns null- the second time the obj
console.log(this.state.modal)
}
为什么会这样?
谢谢!
【问题讨论】: