我正在使用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
组件,一切正常。
答案 0 :(得分:0)
我认为当用户未登录时,它不会渲染您的组件,因为它会进入此if语句的其他部分。除非用户已登录,否则它永远不会路由到大约页面。
return user ? <C {...routeProps} /> : <Redirect to="/login" />;