最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React router render prop route always re-renders components - Stack Overflow

programmeradmin0浏览0评论

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

Route1:

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

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

Route2:

 <Route
     path="/dashboard"
     ponent={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 ponent, how can I use the render prop (or another approach) and also prevent unnecessary ponent re-renders?

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

Route1:

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

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

Route2:

 <Route
     path="/dashboard"
     ponent={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 ponent, how can I use the render prop (or another approach) and also prevent unnecessary ponent re-renders?

Share Improve this question asked Sep 27, 2018 at 3:35 DogDog 2,9167 gold badges34 silver badges72 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论