嵌套状态的React性能



我在这里读了很多文章,建议不要在React中使用深度嵌套的状态对象。

但是,这些缺点是否适用于单个级别对象的状态?这两个例子的性能有什么不同吗?

第一个例子会像第二个例子一样引起重读吗?在这么小的规模上,这有关系吗?

const [example, setExample] = useState({
group1property1: '',
group1property2: '',
group2property1: '',
group2property2: '',
});
const [example2, setExample2] = useState({
group1: {
property1: '',
property2: '',
},
group2: {
property1: '',
property2: '',
}
});

这两个示例之间有性能差异吗?

否。当状态原子被重新分配时(您应该已经知道,您不能只在内部修改对象/数组状态原子(,组件就会更新。

// 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}}));

在这样小的规模上,这有关系吗?

可能不会。

最新更新