【问题标题】:React performance of nested state嵌套状态的反应性能
【发布时间】:2022-01-06 22:35:53
【问题描述】:

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

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

第一个示例会导致与第二个示例一样多的重新渲染吗?像这样的小规模还有关系吗?

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

【问题讨论】:

    标签: javascript reactjs performance react-state react-state-management


    【解决方案1】:

    这两个例子在性能上有区别吗?

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

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

    在这么小的范围内它甚至重要吗?

    可能不会。

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2022-06-13
      • 2021-01-26
      • 2019-06-13
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2021-08-11
      相关资源
      最近更新 更多