React Hooks - 如何实现 shouldComponentUpdate? [英] React Hooks - How do I implement shouldComponentUpdate?
问题描述
我知道你可以通过传递一个数组作为可选的第二个参数来告诉 React 跳过一个效果.
I know you can tell React to skip an effect by passing an array as an optional second argument.
例如:
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
但是如果我想控制比较怎么办?添加我自己的比较逻辑.
我希望像 React.memo
这样的东西可以将函数作为第二个参数传递.
I would expect something like React.memo
that you can pass a function as a second argument.
推荐答案
在上面的评论中 Gabriele Petrioli 链接到解释如何实现 shouldComponentUpdate 的 React.memo 文档.我在谷歌上搜索 shouldComponentUpdate + useEffect + "react hooks" 的组合,结果是这样的.因此,在使用链接文档解决了我的问题后,我想我也会将信息带到这里.
In a comment above Gabriele Petrioli links to the React.memo documentation that explains how to implement shouldComponentUpdate. I was googling combinations of shouldComponentUpdate + useEffect + "react hooks", and this came up as the result. So after solving my problem with the linked documentation I thought I would bring the information here as well.
这是实现 shouldComponentUpdate 的旧方法:
This is the old way of implementing shouldComponentUpdate:
class MyComponent extends React.Component{
shouldComponentUpdate(nextProps){
return nextProps.value !== this.props.value;
}
render(){
return (
<div>{"My Component " + this.props.value}</div>
);
}
}
新的 React Hooks 方式:
The New React Hooks way:
React.memo(function MyComponent (props) {
return <div>{ "My Component " + props.value }</div>;
})
我知道您可能在问题中提出了更多要求,但对于来自 Google 的任何人,他们正在寻找如何使用 React Hooks 实现 shouldComponentUpdate,您就可以了.
I know you were probably asking for more in your question, but for anyone coming from Google looking for how to implement shouldComponentUpdate using React Hooks, there you go.
文档在这里:how-do-i-implement-shouldcomponentupdate
这篇关于React Hooks - 如何实现 shouldComponentUpdate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!