惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
L
LangChain Blog
C
Check Point Blog
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
美团技术团队
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
aimingoo的专栏
aimingoo的专栏
S
SegmentFault 最新的问题
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
腾讯CDC
B
Blog
G
Google Developers Blog
The Cloudflare Blog
P
Proofpoint News Feed

时间的朋友

Windows 命令行密码重置 Anaconda安装 typescript 注解解读1 Konvajs Shape加载自定义图片 sshpass 使用 why-is-node-running webgl笔记 SharedArrayBuffer is not defined blender 常用快捷键 | 时间的朋友 vue -- v3.4commit提交记录2 vue2 升级vue3报错问题整理 着色器 expressjs 源码 hyper-V arch linux 网络配置 element input数字格式化 three 拼接货架 WebAudio笔记 Windows nginx重启bat脚本 vue -- v3.4commit提交记录 URI malformed vue3 -- Class 对象在组件中使用范例 | 时间的朋友 ruby 安装和升级 element-plus 老版本cascader使用卡死问题 vue3 内置Transition组件 | 时间的朋友 前端memo的实现 | 时间的朋友 Vue -- vue-class-component源码 | 时间的朋友 linux 优化脚本 typescript 装饰器 | 时间的朋友 microbundle 源码 | 时间的朋友 WSL2问题解决WslRegisterDistribution failed with error: 0x800701bc
React Rerender重绘原理
2022-05-08 · via 时间的朋友

react rerender原理 🔗

react中组件重绘是一个不可避免的问题,因为react中组件的更新方式就是旧组件销毁,新组件替代旧组件的形式。而且react组件中以树的形式进行构建,必然带来的就是父组件更新,其所有的子组件都会更新

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 父组件
function ListComp() {
  const [list, setList] = useState([
    {
      id: 1,
      value: "",
    },
    {
      id: 2,
      value: "",
    },
    {
      id: 3,
      value: "",
    },
  ]);

  return (
    <div>
      <div>{JSON.stringify(list)}</div>

      <div>
        {list.map((item, idx) => (
          <Item
            key={idx}
            {...item}
            onChange={(id: number, value: any) => {
              setList(
                list.map((item) => {
                  if (item.id === id) {
                    item.value = value;
                  }
                  return item;
                })
              );
            }}
          ></Item>
        ))}
      </div>
    </div>
  );
}

// 子组件
function Item({ id, value, onChange }) {
  return (
    <div>
      <h3>{id}</h3>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(id, e.target.value)}
      />
    </div>
  );
}

在只输入一个输入框的同时,其他子组件都在重新渲染

同样只更新父组件的同时,子组件也会更新

当组件的状态发生变化时,组件及其子组件都会rerender

如果不想子组件发生不必要的render,使用memo包裹一下组件

1
const Item = memo(() => <div>Item</div>)

可以看到父组件更新后,子组件不会再发生rerender

我重新包裹一下我们的子组件Item

1
const ItemWrapper = memo(Item)

子组件还是会发生不必要的rerender

当组件使用memo包裹后还会发生rerender,说明组件又props发生了变化

排查后就是onChange属性发生了变化, 每次父组件rerender后子组件都会重新生产一个onChange事件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
onChange={(id: number, value: any) => {
  setList(
    list.map((item) => {
      if (item.id === id) {
        item.value = value;
      }
      return item;
    })
  );
}}

使用useCallback对属性进行缓存,useCallback会生成一个函数缓存

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  const onChange = useCallback((id: any, value: any) => {
    setList((preList) =>
      preList.map((item) => {
        if (item.id === id) {
          item.value = value;
        }
        return item;
      })
    );
  }, []);

最终代码 🔗

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const Item: React.FC<{ id: any; value: any; onChange: any }> = memo(({ id, value, onChange }: any) => {
  return (
    <div
      style={{
        width: "200px",
        display: "inline-block",
      }}
    >
      <h3>{id}</h3>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(id, e.target.value)}
      />
    </div>
  );
});

const Parent = () => {
  const [items, setItems] = useState([
    { value: "", id: 1 },
    { value: "", id: 2 },
    { value: "", id: 3 },
  ]);
  const onChange = useCallback((id: any, value: any) => {
    setItems(
      items => items.map((item) => {
        if(item.id === id) {
          item.value = value
        }
        return item;
      })
    );
  }, []);

  return (
    <div style={{ padding: "20px" }}>
      <div>{JSON.stringify(items)}</div>
      {items.map((item, index) => (
        <Item key={index} id={item.id} value={item.value} onChange={onChange} />
      ))}
    </div>
  );
};

https://alexsidorenko.com/blog/react-list-rerender/