【发布时间】:2017-09-13 13:35:12
【问题描述】:
我正在使用带有代码拆分功能的 react-router。像AuthenticatedRoute 这样的动态路由似乎不能很好地处理它。
如果用户转到About 路由,登录并返回About 路由(不刷新页面),则不会显示任何内容,因为About 路由代码拆分块没有得到已替换/更新,但没有导入 About 组件。
代码:
路线
import React from 'react';
import { Route } from 'react-router-dom'
import asyncComponent from "./AsyncComponent";
import AuthenticatedRoute from "./AuthenticatedRoute";
const AsyncHome = asyncComponent(() => import("../../containers/Home/Home"));
const AsyncAbout = asyncComponent(() => import("../../containers/About/About"));
const AsyncLogin = asyncComponent(() => import("../../containers/Login/Login"));
const Routes = () => (
<main>
<Route exact path="/" component={AsyncHome} />
<AuthenticatedRoute exact path="/about" component={AsyncAbout} />
<Route exact path="/login" component={AsyncLogin} />
</main>
)
export default Routes
AuthenticatedRoute
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Route, Redirect } from 'react-router-dom';
class AuthenticatedRoute extends Component {
render() {
const { props } = this;
const { component: C, user, ...newProps } = props;
const renderComponent = (routeProps) => {
return user ? <C {...routeProps} /> : <Redirect to="/login" />;
}
return <Route {...newProps} render={renderComponent} />
}
}
const mapStateToProps = state => ({
user: state.auth.user
})
const mapDispatchToProps = dispatch => bindActionCreators({
}, dispatch)
export default connect(
mapStateToProps,
mapDispatchToProps,
)(AuthenticatedRoute)
问题似乎与块的生成有关。如果 About 路由块是在用户未登录的情况下创建的,则该块将没有 About 组件。如果我在登录后刷新页面,About 路由块那里有About 组件并且一切正常。
【问题讨论】:
标签: reactjs webpack react-router react-router-v4 code-splitting