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

时间:2020-11-01 16:37:01

标签: javascript reactjs react-hooks react-functional-component

我有一个Class React组件,如果浏览器pathName为/ exp,则使用功能性的Hook组件

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

如果道具未更改,如何防止Example挂钩重新安装?

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>
         )
}

1 个答案:

答案 0 :(得分:1)

const Chat = React.memo(props => {
  console.log("Greeting Comp render");
  return <></>
});

export default Chat   
//This worked for me

您可以使用React.memo并在更改道具时进行渲染

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(如果是类组件)

shouldComponentUpdate(nextProps, nextState)

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