切换链接时防止反应路由器重新创建组件 [英] Prevent react-router re-creating component when switching links

查看:32
本文介绍了切换链接时防止反应路由器重新创建组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在顶层有许多导航链接,当您在链接之间切换时,它们可以切换页面级组件.某些页面具有创建成本高昂的复杂网格组件.我注意到每次切换页面时 react-router 都会构造组件.有没有办法缓存传递给路由的组件?,即 PositionsPage

解决方案

这是 React 整体(而不仅仅是 react-router)的一个非常重要的性能考虑.

默认情况下,React 会针对 propsstate 中的任何更改重新渲染完整的 DOM 树.

这里总结了 React 高级性能文档 建议.

使用生产版本

注意:组件的正确性是自动处理的.没什么可担心的.

这应该相当简单.以下 webpack.config.js 插件部分片段应确保 NODE_ENV 变量到达 React 源代码.

<代码> ...插件: [new CommonsChunkPlugin('bundle.js'),新的 webpack.DefinePlugin({'process.env':{'NODE_ENV': JSON.stringify(process.env.NODE_ENV)}})]...

现在只需确保 NODE_ENV=production webpack -p.

这可确保跳过所有这些警告/错误和 propTypes 检查.

避免协调 DOM

警告:您必须处理 propsstate 的所有可能条件矩阵(如果需要),以确保不会搞砸渲染的正确性.

这是必须实现的回调签名.每当任何 stateprop 值更改时都会调用此方法.

shouldComponentUpdate: function(nextProps, nextState) {//@TODO 你的逻辑在这里//返回真更新,否则返回假返回真;}

<块引用>

记住 React 会经常调用这个函数,所以实施必须很快.

I have a number of nav links at the top level that switch page level components in and out when you switch between the links. Some pages have complex grid components that are expensive to create. I noticed that react-router constructs the component every time a page is switched. Is there a way to cache the component passed into a route?, i.e PositionsPage

<Route path="/positions" component={PositionsPage} />

解决方案

This is a very important performance consideration in React as a whole (and not just react-router).

By default design, React re-renders the complete DOM tree for any change in props or state.

Here is a summary of techniques that the React documentation for Advanced Performance suggests.

Use the production build

NOTE: Correctness of components is automatically taken care of. Nothing to worry.

This should be fairly simply. The following webpack.config.js plugins section snippet should make sure that the NODE_ENV variable reaches the React source code.

  ...
  plugins: [
    new CommonsChunkPlugin('bundle.js'),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }
    })
  ]
  ...

Now just ensure the NODE_ENV=production webpack -p.

This ensures that all those warnings/errors and propTypes checking is skipped.

Avoiding reconciling the DOM

WARNING: You must handle all possible condition matrices (if needed) of props and state to make sure you don't mess up the correctness of rendering.

This is the callback signature which must be implemented. This is called whenever any state or prop value changes.

shouldComponentUpdate: function(nextProps, nextState) {
  // @TODO your logic here
  // return true to update, false otherwise
  return true;
}

Keep in mind that React will invoke this function pretty often, so the implementation has to be fast.

这篇关于切换链接时防止反应路由器重新创建组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆