2

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

4

1 回答 1

0

我认为当用户未登录时,它不会呈现您的组件,因为它进入了 if 语句的 else 部分。除非用户登录,否则它永远不会路由到 about 页面。

return user ? <C {...routeProps} /> : <Redirect to="/login" />;
于 2017-09-13T19:31:54.880 回答