首页 > 解决方案 > 反应路由器渲染道具路由总是重新渲染组件

问题描述

我正在使用 React Router 并且因为需要将需要组件的函数传递到路由中,所以我正在使用渲染道具渲染组件。但是,将路由作为渲染道具传递总是会导致组件重新渲染。我已经尝试了所有可能的 lifeCycle 钩子,例如 shouldComponentUpdate 和 ComponentDidUpdate,但没有什么能阻止组件重新渲染。该路由结构如下图所示:

路线1:

<Route
  path='/dashboard'
  render={() => dashboardOperator(<Dashboard />)}
/>

相反,如果我只是以传统方式传递组件,它不会触发自动重新渲染。

路线2:

 <Route
     path="/dashboard"
     component={DashboardComponent}
 />

但是,这种路由方法并不有效,因为它不允许将函数传递到路由中。

由于生命周期钩子似乎不能有效地防止 Route1(渲染道具方法)重新渲染组件,我如何使用渲染道具(或其他方法)并防止不必要的组件重新渲染?

标签: javascriptreactjsreact-router

解决方案


尝试这样的事情:

class App extends React.PureComponent {
  renderDashboardPage() {
    return dashboardOperator(<Dashboard />)
  }

  render() {
    return (
      <Route
        path='/dashboard'
        render={this.renderDashboardPage}
      />
    );
  }
}

这应该可以工作,因为函数/对象引用在重新渲染时保持不变,所以 React 会意识到 props 没有改变。虽然,要小心过早的优化。


推荐阅读