javascript - React Router 4 + 代码分割 |组件重新安装

标签 javascript reactjs react-router-v4 code-splitting react-loadable

我有下一个代码:

import React from 'react'
import Loadable from 'react-loadable'
import { Route } from 'react-router-dom'

class App extends React.Component {
    state = {
        kappa: false
    }

    componentDidMount() {
        setTimeout(() => {
            setState({ kappa: true })
        }, 1000)
    }

    render() {
        return (
            <div className="app">
                <Route exact path="/:locale/" component={Loadable({
                    loader: () => import('../views/IndexPage/index.jsx'),
                    loading: () => "loading"
                })} />
                <Route exact path="/:locale/registration" component={Loadable({
                    loader: () => import('../views/Registration/index.jsx'),
                    loading: () => "loading"
                })} />

                {this.state.kappa && <p>Hey, Kappa-Kappa, hey, Kappa-Kappa, hey!</p>}
            </div>
        )
    }
}

当状态更新时(kappa 变为 true 并且 p 出现),事件路由上的组件(无论它是什么 - IndexPageRegistration) 重新安装。如果我在应用程序中手动导入组件并将其传递到 Route 而不进行代码分割,则路由上的组件不会重新安装(这是非常明显的)。

我还尝试了 webpack 的动态导入,如下所示:

<Route path="/some-path" component={props => <AsyncView {...props} component="ComponentFolderName" />

其中 import(`/path/to/${this.props.component}/index.jsx`)componentDidMount 中运行并填充 AsyncView 的状态,其行为类似于 Loadable 情况。

我想,问题是 Routecomponent 是一个匿名函数

问题是:如何避免重新挂载路由组件?

最佳答案

嗯,这种行为是正常的,并在 React Router 4 文档中有记录:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

render 与 React Loader 和 webpack 的代码分割都可以正常工作。

关于javascript - React Router 4 + 代码分割 |组件重新安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791228/

相关文章:

reactjs - react : Is manual memoization necessary?

javascript - 无法使用 angularjs 将 json 数据绑定(bind)到表

javascript - 如何在 vaadin(例如 OpenStreetMap)中集成 javascript?

json - 将 Ant Design Form 与 Modal 集成

react-router - 在React Router 4中,如何使用正则表达式来否定路由/路径?

reactjs - React 路由器 URL 参数不起作用

javascript - 如何在 React 中使用 # 个 url 来保存组件应用程序状态?

javascript - jquery中如何检查元素

javascript - 带 jquery ui slider 的 Html5 Canvas

javascript - 我怎样才能只更新部分状态