我正在尝试使用新的 Hooks 从类组件转向功能组件。然而,感觉与useCallback
类组件中的类函数不同,我会得到不必要的子元素渲染。
下面我有两个相对简单的片段。第一个是我编写为类的示例,第二个是我将示例重写为功能组件。目标是让功能组件获得与类组件相同的行为。
类组件测试用例
class Block extends React.PureComponent {
render() {
console.log("Rendering block: ", this.props.color);
return (
<div onClick={this.props.onBlockClick}
style = {
{
width: '200px',
height: '100px',
marginTop: '12px',
backgroundColor: this.props.color,
textAlign: 'center'
}
}>
{this.props.text}
</div>
);
}
};
class Example extends React.Component {
state = {
count: 0
}
onClick = () => {
console.log("I've been clicked when count was: ", this.state.count);
}
updateCount = () => {
this.setState({ count: this.state.count + 1});
};
render() …
Run Code Online (Sandbox Code Playgroud)