我定义了一个场景:我们有一个使用父母的道具和自身状态的组件。
下面有两个组件 DC 和 JOKER 以及我的步骤:
- 点击 DC 的按钮
- 直流设置计数
- JOKER 将以旧状态呈现
- 运行 useEffect 和 setCount
- 小丑再次渲染
我想问一下为什么 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"))
原文由 Stephen Kingsley 发布,翻译遵循 CC BY-SA 4.0 许可协议