我定义了一个场景:我们有一个使用父级props和自身状态的组件。
下面有两个组件 DC 和 JOKER 以及我的步骤:
- 单击 DC 的按钮
- DC设置计数
- JOKER 将使用旧状态渲染
- 运行 useEffect 和 setCount
- JOKER 再次渲染
我想问一下为什么 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"))