React Hooks-如何实现shouldComponentUpdate?

Ida*_*gan 23 reactjs react-hooks

我知道您可以通过将数组作为可选的第二个参数传递来告诉React跳过效果。

例如:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
Run Code Online (Sandbox Code Playgroud)

但是,如果我想控制比较怎么办?添加我自己的比较逻辑。

我希望React.memo可以将一个函数作为第二个参数传递给您。

PAT*_*ION 43

在上面的评论中,Gabriele Petrioli链接到 React.memo 文档,该文档解释了如何实现 shouldComponentUpdate。我在谷歌上搜索 shouldComponentUpdate + useEffect + "react hooks" 的组合,结果就是这样。因此,在使用链接文档解决了我的问题后,我想我也会将信息带到这里。

这是实现 shouldComponentUpdate 的旧方法:

class MyComponent extends React.Component{
  shouldComponentUpdate(nextProps){
    return nextProps.value !== this.props.value;
  }
  render(){
    return (
     <div>{"My Component " + this.props.value}</div>
    );  
 }
}
Run Code Online (Sandbox Code Playgroud)

新的 React Hooks 方式:

React.memo(function MyComponent (props) {

  return <div>{ "My Component " + props.value }</div>;

}) 
Run Code Online (Sandbox Code Playgroud)

我知道你可能在你的问题中要求更多,但是对于来自谷歌的任何人寻找如何使用 React Hooks 实现 shouldComponentUpdate 的人来说,你去吧。

文档在这里: how-do-i-implement-shouldcomponentupdate


Avi*_*ash 24

除了 PAT-O-MATION 的答案之外,
React.memo 还接受第二个参数,该参数是可用于确定组件是否应呈现的函数。

如果函数返回 true,则组件不会在该 prop 更改时重新渲染,相反,当返回值为 false 时它会更新

function SomeComp({prop1, prop2}) {
    return(
        ..
    )

}
React.memo(SomeComp, (props, nextProps)=> {
    if(props.prop1 === nextProps.prop1) {
        // don't re-render/update
        return true
    }
})
Run Code Online (Sandbox Code Playgroud)

注意:组件只会在回调函数返回 false 时重新渲染,因此在上述情况下,即使 prop2 值发生变化,它也不会重新渲染


Wil*_*l59 5

An alternative might be to use useRef to hold your data, and use useState ONLY to store the data you want to display. Sometimes this works better than the memo approach: I've had a case recently where React was still rendering needlessly when using React.memo, and it was messing up some PIXI display. The approach below fixed it for me... hopefully I did not do an anti-pattern :-)

const countRef = useRef(0);
const [countDisplay, setCountDisplay] = useState(0);

yourUpdateFunction = () => {
  // An example of function where count gets updated,
  // and which will affect the display only when the
  // counter is even...
  countRef.current = countRef.current + 1;
  if ((countRef.current % 2) === 0) setCountDisplay(countRef.current);
}

return (<p>{countDisplay}</p>);
Run Code Online (Sandbox Code Playgroud)


Vla*_*nin 5

除了Avinash 的回答。返回值的重要说明:

shouldComponentUpdate() {
  // returns true by default
  // return false if you don't need re-render
}
Run Code Online (Sandbox Code Playgroud)
export default React.memo(Component, (props, nextProps) => {
  if(props.prop1 === nextProps.prop1) {
    // return true if you don't need re-render
  }
})
Run Code Online (Sandbox Code Playgroud)