gpt4 book ai didi

javascript - React Hooks 渲染两次

转载 作者:行者123 更新时间:2023-12-03 13:23:50 24 4
gpt4 key购买 nike

我定义了一个场景:我们有一个使用父级 Prop 和自身状态的组件。

有两个组件 DC 和 JOKER,我的步骤如下:

  1. 点击 DC 按钮
  2. DC 设置计数
  3. JOKER 将以旧状态渲染
  4. 运行 useEffect 和 setCount
  5. JOKER 再次渲染

enter image description here

我想问为什么 JOKER 渲染两次(第 3 步和第 5 步)而第一次渲染浪费了性能。 我只是不想执行第 3 步如果在类组件中我可以使用 componentShouldUpdate 来避免它。但 Hooks 有同样的东西吗?

我的代码如下,或者打开这个网站https://jsfiddle.net/stephenkingsley/sw5qnjg7/

import React, { PureComponent, useState, useEffect, } from 'react';

function JOKER(props) {
const [count, setCount] = useState(props.count);
useEffect(() => {
console.log('I am JOKER\'s useEffect--->', props.count);
setCount(props.count);
}, [props.count]);

console.log('I am JOKER\'s render-->', count);
return (
<div>
<p style={{ color: 'red' }}>JOKER: You clicked {count} times</p>
</div>
);
}

function DC() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => {
console.log('\n');
setCount(count + 1);
}}>
Click me
</button>
<JOKER count={count} />
</div>
);
}

ReactDOM.render(<DC />, document.querySelector("#app"))

最佳答案

It's an intentional feature of the StrictMode. This only happens indevelopment, and helps find accidental side effects put into therender phase. We only do this for components with Hooks because thoseare more likely to accidentally have side effects in the wrong place.-- gaearon commented on Mar 9, 2019

关于javascript - React Hooks 渲染两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58603209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com