我有下一个代码:
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
出现),事件路由上的组件(无论它是什么 - IndexPage
或 Registration
) 重新安装。如果我在应用程序中手动导入组件并将其传递到 Route
而不进行代码分割,则路由上的组件不会重新安装(这是非常明显的)。
我还尝试了 webpack 的动态导入,如下所示:
<Route path="/some-path" component={props => <AsyncView {...props} component="ComponentFolderName" />
其中 import(`/path/to/${this.props.component}/index.jsx`)
在 componentDidMount
中运行并填充 AsyncView
的状态,其行为类似于 Loadable
情况。
我想,问题是 Route
的 component
是一个匿名函数
问题是:如何避免重新挂载路由组件?
最佳答案
嗯,这种行为是正常的,并在 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/