Dog*_*Dog 5 javascript reactjs react-router
我正在使用 React Router,因为需要将一个需要组件的函数传递到路由中,所以我正在使用渲染道具渲染组件。但是,将路由作为渲染道具传递总是会导致组件重新渲染。我已经尝试了所有可能的生命周期钩子,比如 shouldComponentUpdate 和 ComponentDidUpdate,但没有什么能阻止组件重新渲染。该路由结构如下图所示:
路线1:
<Route
path='/dashboard'
render={() => dashboardOperator(<Dashboard />)}
/>
Run Code Online (Sandbox Code Playgroud)
相反,如果我只是以传统方式传递组件,它不会触发自动重新渲染。
路线2:
<Route
path="/dashboard"
component={DashboardComponent}
/>
Run Code Online (Sandbox Code Playgroud)
但是,这种路由方式并不有效,因为它不允许将函数传递到路由中。
由于生命周期钩子似乎不能有效阻止 Route1(渲染道具方法)重新渲染组件,我如何使用渲染道具(或其他方法)并防止不必要的组件重新渲染?
尝试这样的事情:
class App extends React.PureComponent {
renderDashboardPage() {
return dashboardOperator(<Dashboard />)
}
render() {
return (
<Route
path='/dashboard'
render={this.renderDashboardPage}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这应该有效,因为函数/对象引用在重新渲染时保持不变,因此 React 将意识到 props 没有改变。虽然,要小心过早的优化。
| 归档时间: |
|
| 查看次数: |
2479 次 |
| 最近记录: |