【问题标题】:Dynamic routes with code splitting chunks don't seem to work带有代码拆分块的动态路由似乎不起作用
【发布时间】: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


    【解决方案1】:

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

    return user ? <C {...routeProps} /> : <Redirect to="/login" />;
    

    【讨论】:

    • 这在用户未登录时按预期工作。如果用户登录但About路由的代码拆分块相同,则会出现问题,这会导致About组件不出现。
    猜你喜欢
    • 2020-12-30
    • 2017-06-13
    • 2017-12-22
    • 2012-12-12
    • 2017-07-15
    • 2021-11-18
    • 2018-02-24
    • 2022-06-11
    • 1970-01-01
    相关资源
    最近更新 更多