我编写了一个自定义逻辑来处理 react-router-dom .v4 中的异步路由加载包。这是完美的工作。但我也听说过有用的包和漂亮的 API 来做同样的事情,比如React-Loadable
. 它有一个问题,我无法在组件的挂载上获取从 Redux 推送的道具/状态,抛出这个包。
在下面的两个示例中,我的代码从custom
样式改写为react-loadable
样式。最后一个是 react-loadable 版本,它不会抛出 state/props。
我的个人代码:
const asyncComponent = getComponent => {
return class AsyncComponent extends React.Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentWillMount() {
const { Component } = this.state
if (!Component) {
getComponent().then(({ default: Component }) => {
const { store } = this.props // CAN GET THE REDUX STORE
AsyncComponent.Component = Component;
this.setState({ Component });
});
}
}
render() {
const { Component } = this.state;
if (Component) {
return <Component {...this.props} />
}
return null;
}
};
};
export default withRouter(asyncComponent(() => import(/* webpackChunkName: "chunk_1" */ './containers/Component')))
相同的代码,但使用 React-Loadable:
const Loading = () => {
return <div>Loading...</div>;
}
const asyncComponent = Loadable({
loader: () => import(/* webpackChunkName: "" */ './containers/Component')
.then(state => {
const { store } = this.props // CANNOT GET THE REDUX STORE!!
}),
loading: Loading
})
export default withRouter(asyncComponent)