我在执行 setState 更改嵌套对象数组的值时遇到问题。下面的代码假设 将 id 2 的问题更改为 answer: true 但不是,怎么了?
this.state = {
questions: [
{
id: 1,
answer: ''
},
{
id: 2,
answer: ''
},
]
}
//I have a click event somewhere
this.setState(
{
questions: this.state.questions.map(q => {
if (q.id === 2) {
return {
...q,
answer: true
}
} else {
return { ...q }
}
})
},
console.log(this.state.questions[1]) // did not see id of 2 being changed to true?
)
最佳答案
console.log(this.state.questions[1])
行在 this.setState
行执行之前执行,这就是打印旧状态的原因到控制台。您应该将此行放在函数中以延迟执行:
this.setState(..., () => console.log(this.state.questions[1]));
此外,如果更改的状态是从当前状态派生的,建议使用函数作为第一个参数,因为 React 不会立即应用新状态,因此 this.state
可能会过时React 应用新状态:
this.setState(state => ({
questions: state.questions.map(q => {
if (q.id === 2) {
return {...q, answer: true};
}
return q;
})
}), () => {
console.log(this.state.questions[1]);
});
关于javascript - 使用 map react setState 对象数组不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435156/