我正在使用带有代码拆分的 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
认证路由
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
组件并且一切正常。