最佳答案
我发现这两部分的反应钩文件有点混乱。哪一个是使用状态钩子更新状态对象的最佳实践?
假设想要进行以下状态更新:
INITIAL_STATE = {
propA: true,
propB: true
}
stateAfter = {
propA: true,
propB: false // Changing this property
}
选择一
从 使用反应钩的文章中,我们得知这是可能的:
const [count, setCount] = useState(0);
setCount(count + 1);
所以我可以这样做:
const [myState, setMyState] = useState(INITIAL_STATE);
然后:
setMyState({
...myState,
propB: false
});
选择二
从 钩子参考文献我们可以看到:
与在类组件中找到的 setState 方法不同,useState 可以 不会自动合并更新对象 通过将函数更新器形式与对象扩展相结合来实现 句法:
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
据我所知,两者都有效。那有什么区别呢?哪一个是最好的练习?我应该使用传递函数(OPTION 2)来访问以前的状态,还是应该使用扩展语法(OPTION 1)来访问当前的状态?