嵌套状态的反应性能

React performance of nested state

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

但是,这些缺点是否适用于单级对象的状态?这两个示例之间有任何性能差异吗?

第一个示例是否会像第二个示例一样引起重新渲染?这么小的规模有关系吗?

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

Is there any performance difference between these two examples?

没有。当状态原子被重新分配时(你应该已经知道你不能只是在内部修改一个 object/array 状态原子),组件被更新。

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

Will the first example cause rerenders just as much as the second?

是的,因为无论如何你都需要浅拷贝外部状态原子来让 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}}));

Does it even matter at such a small scale like this?

可能不会。