[英]React router render prop route always re-renders components
我正在使用React Router,因為需要將需要組件的函數傳遞到路由中,所以使用渲染道具渲染組件。 但是,將路徑作為渲染道具傳遞總是會導致組件重新渲染。 我已經嘗試了所有可能的lifeCycle掛鈎,例如shouldComponentUpdate和ComponentDidUpdate,但沒有任何東西阻止組件重新渲染。 這種路線結構如下所示:
ROUTE1:
<Route
path='/dashboard'
render={() => dashboardOperator(<Dashboard />)}
/>
相反,如果我只是以傳統方式傳遞組件,它不會觸發自動重新渲染。
路徑2:
<Route
path="/dashboard"
component={DashboardComponent}
/>
但是,這種路由方法無效,因為它不允許將函數傳遞到路由中。
由於生命周期鈎子似乎不能有效地阻止Route1(渲染道具方法)重新渲染組件,我如何使用渲染道具(或其他方法)並防止不必要的組件重新渲染?
嘗試這樣的事情:
class App extends React.PureComponent {
renderDashboardPage() {
return dashboardOperator(<Dashboard />)
}
render() {
return (
<Route
path='/dashboard'
render={this.renderDashboardPage}
/>
);
}
}
這應該工作,因為函數/對象引用在重新渲染時保持不變,因此React將意識到道具沒有改變。 雖然,請注意預成熟優化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.