React Hook 函数组件防止重新渲染

React Hook function Component prevent re-render

我有一个 Class React 组件,如果浏览器路径名是 /exp

,它会使用功能性 Hook 组件

当页面加载时,我的应用程序组件更改状态大约 3-4 次,

如果 prop 没有改变,如何防止 Example hook 重新挂载?

import React, { useState } from 'react';

 function Example() {
  console.log("i mounted")
  }

__

export default class App extends Component {
state={key:"value"}   <--------------------------------------MAIN APP STATE CHANGES 3 times
componentDidMount(){
//I change App state 3 times with conditional code 
}

 render() {
    return (
      <Router>
        <Switch>
        <Route path="/exp">
            <Example prop="I have not changed"  />  <-----------------PREVENT MULTIPLE MOUNTINGS
        </Route>
            </Switch>
         </Router>
         )
}
const Chat = React.memo(props => {
  console.log("Greeting Comp render");
  return <></>
});

export default Chat   
//This worked for me

您可以使用 React.memo 并在 prop 更改时渲染

function MyComponent(props) {
  /* render using props */
}

function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);

shouldcomponentupdate 如果 class 组件

shouldComponentUpdate(nextProps, nextState)

注意:此方法仅作为性能优化存在。不要依赖它来“阻止”渲染,因为这会导致错误。