![](/img/trans.png)
[英]React setState doesn't work with array.prototype.splice
[英]react setState array of object using map doesn't work?
我有问题做一个setState更改嵌套对象数组的值。 下面的代码假设改变id 2的问题来回答: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不会立即应用新状态,因此当React应用新状态时this.state
可能会过时:
this.setState(state => ({
questions: state.questions.map(q => {
if (q.id === 2) {
return {...q, answer: true};
}
return q;
})
}), () => {
console.log(this.state.questions[1]);
});
您没有调用setState
回调。 试试这样:
this.setState(
{
questions: this.state.questions.map(q => {
if (q.id === 2) {
return {
...q,
answer: true
};
}
return { ...q };
})
},
() => console.log(this.state.questions[1]) // did not see id of 2 being changed to true?
);
但是,由于您使用当前状态再次更新状态,因此最好使用函数setState。
this.setState(
currentState => ({
questions: currentState.questions.map(q => {
if (q.id === 2) {
return {
...q,
answer: true
};
}
return { ...q };
})
}),
() => console.log(this.state.questions[1])
);
此外,您不必在回调中将状态记录到setState
。 您可以在render
方法中记录状态,而不必费力地调整setState
的回调。
this.setState(
currentState => ({
questions: currentState.questions.map(q => {
if (q.id === 2) {
return {
...q,
answer: true
};
}
return { ...q };
})
})
);
....
render() {
console.log( this.state );
....
}
我认为这是因为Array.map返回一个数组。 尝试:
this.setState(
{
questions: this.state.questions.map(q => {
if (q.id === 2) {
q.answer = true;
}
return q;
})
},
console.log(this.state.questions[1]) // did not see id of 2 being changed to true?
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.