简体   繁体   中英

React router render prop route always re-renders components

I am using React Router and because a function that takes a components needs need to be passed into the route, am rendering the components with a render prop. However, passing in a route as a render prop always results in the component re-rendering. I have tried all the possible lifeCycle hooks, such as shouldComponentUpdate and ComponentDidUpdate, but nothing prevents the component from re-rendering. This route structure is shown below:

Route1:

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

Conversely, if I just pass the component in the traditional way, it does not trigger an automatic re-render.

Route2:

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

However, this routing approach is not effective because it does not allow the function to be passed into the route.

Since lifecycle hooks do not appear to be effective in preventing Route1 (the render prop approach) from re-rendering the component, how can I use the render prop (or another approach) and also prevent unnecessary component re-renders?

Try something like this:

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

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

This should work because the function/object reference stays the same across re-renders, so React will realize the props have not changed. Although, be careful about pre-mature optimization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM