【问题标题】:React Hook function Component prevent re-renderReact Hook 功能组件防止重新渲染
【发布时间】:2021-02-14 10:38:59
【问题描述】:

我有一个 Class React 组件,如果浏览器路径名是 /exp,它使用功能性 Hook 组件

当页面加载时,我的应用组件的状态变化大约 3-4 次,

如果道具没有改变,我如何防止示例钩子重新安装?

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

【问题讨论】:

  • 考虑使用export default React.memo(App)
  • 嗯,App 不是功能组件,我不认为我可以在那里使用 React.memo

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


【解决方案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)

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

【讨论】:

  • 我必须阅读文档,我进行了复制粘贴,但 MyComponent 仍在多次渲染
  • 你可以尝试使用 PureComponent reactjs.org/docs/react-api.html#reactpurecomponent
  • const Chat = React.memo(props => { console.log("Greeting Comp render"); return > });导出默认聊天这有效
猜你喜欢
  • 2021-09-29
  • 2020-03-27
  • 2019-07-28
  • 2020-06-12
  • 1970-01-01
  • 2020-03-17
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多