【发布时间】:2021-09-09 00:08:09
【问题描述】:
我定义了一个场景:我们有一个使用父级道具和自身状态的组件。
下面有两个组件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"))
【问题讨论】:
-
因为您正在使用不会重新渲染的
setCount(props.count);行删除更新 JOKER 本地状态。更多信息reactjs.org/docs/hooks-effect.html -
@ReyanshMishra 我担心第 3 步。我知道当我在 JOKER 中设置计数时,JOKER 会再次渲染。如果在类组件中,我可以使用 componentShouldUpdate 来避免它。现在 hooks 有同样的东西还是 api?
-
useEffect设置为在第一次渲染之后运行,以便开发人员在 effect 运行之前在屏幕上渲染某些内容,从而提高用户感知的性能指标。组件的性能不等于它运行的渲染次数。 -
@StephenKingsley 虽然有这个计划,但他们并没有这样做,因为如果您忘记将字段添加到监视字段,或者如果您正在使用它会导致很多混乱行为具有私有状态的复合挂钩调用。
标签: javascript reactjs react-hooks rerender