我在這里閱讀了很多建議不要在 React 中使用深度嵌套的狀態物件的帖子。
但是,這些缺點是否適用于單級物件的狀態?這兩個示例之間是否有任何性能差異?
第一個示例會導致與第二個示例一樣多的重新渲染嗎?像這樣的小規模甚至有關系嗎?
const [example, setExample] = useState({
group1property1: '',
group1property2: '',
group2property1: '',
group2property2: '',
});
const [example2, setExample2] = useState({
group1: {
property1: '',
property2: '',
},
group2: {
property1: '',
property2: '',
}
});
uj5u.com熱心網友回復:
這兩個示例之間是否有任何性能差異?
不。當狀態原子被重新分配時(你應該已經知道你不能只在內部修改物件/陣列狀態原子),組件就會更新。
// not good; will not cause update since identity of `example` doesn't change
example.group1property1 = 8;
setExample(example);
// good; example is shallow-copied and updated
setExample(example => ({...example, group1property1: 8}));
第一個示例會導致與第二個示例一樣多的重新渲染嗎?
是的,因為無論如何你都需要淺拷貝外部狀態原子以讓 React 獲取內部物件中的更改。只是深度物件的更新有點乏味,除非你使用類似immer 的東西。
// not good; will not cause update, etc. etc.
example.group1.property1 = 8;
setExample(example);
// good; example is shallow-copied, as is group1
setExample(example => ({...example, group1: {...example.group1, ...property1: 8}}));
像這樣的小規模甚至有關系嗎?
可能不是。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/404895.html
標籤:
下一篇:完成一個稀疏的時間線
