javascript - 反应路由器渲染道具路由总是重新渲染组件
问题描述
我正在使用 React Router 并且因为需要将需要组件的函数传递到路由中,所以我正在使用渲染道具渲染组件。但是,将路由作为渲染道具传递总是会导致组件重新渲染。我已经尝试了所有可能的 lifeCycle 钩子,例如 shouldComponentUpdate 和 ComponentDidUpdate,但没有什么能阻止组件重新渲染。该路由结构如下图所示:
路线1:
<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 会意识到 props 没有改变。虽然,要小心过早的优化。
推荐阅读
- python - 我不明白为什么我不能在 Python 中按索引获取记录?
- python - 使用 bash 将 Python 添加到路径中
- oracle - Oracle 将游标的输出连接到 CLOB
- javascript - TypeError:无法读取离子应用程序 null 的属性“样式”
- node.js - 如何将 node.js 应用程序推送到具有本地依赖关系的 heroku?
- powershell - 从 PowerShell 中的文件名中提取日期
- python - 如何使PDF可填写?
- c++ - 为什么函数“constexpr”说明符应该匹配?
- java - 我怎样才能让这个数据管理器真正工作 Java Spigot Plugin
- jwt - 使用 JWT 创建的 Gmail 服务帐户访问令牌不起作用,返回