在 JavaScript 中,string, integer and boolean values are immutable, but objects and arrays are mutable.
如果状态具有两种类型的值,我们应该如何更新 React 中的状态?
例如
constructor(props) {
super(props);
this.state = {
success: false,
error: false,
errorMessages: {}
};
}
假设您需要立即更新所有属性(success
、error
、errorMessages
),最好的方法是什么实现了吗?
至少我确信 errorMessages
不应该直接更新,因为它本质上是可变的,但是其余的呢?
我尝试了类似以下的操作,但最终得到了错误的结果。
const errorMessages = {
...this.state,
"errorMessages": error.response.data,
};
this.setState({
errorMessages,
success: false,
error: true,
});
//The errorMessages property will have "success" and "error" property in it
最佳答案
只要您为 errorMessages
提供新值,React 就会正确更新状态。你不会直接在这里改变状态,你只是为字段提供一个新值,React 将进行必要的改变:
this.setState({
errorMessages: error.response.data
success: false,
error: true,
});
关于javascript - react : how to update states which have both mutable and immutable values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46800259/