首页 > 解决方案 > Reactjs在点击重新加载按钮时重新加载当前路由,而不是整个应用程序

问题描述

我有一个基本的 react-router 设置,带有 Switch,如下所示:

import React from "react"
import {Route, Switch } from "react-router-dom"

import AuthenticatedRoute from "./components/AuthenticatedRoute"
import UnauthenticatedRoute from "./components/UnauthenticatedRoute"

import Home from './containers/Home'
import Login from './containers/Login'
import Books from './containers/Books'


import NotFound from './containers/NotFound'


export default ({ childProps }) => (
  <Switch>
    <AuthenticatedRoute path="/" exact component={Home} props={childProps} />
    <UnauthenticatedRoute path="/login" exact component={Login} props={childProps} />
    <AuthenticatedRoute path="/books" exact component={Books} props={childProps} />

    { /* Finally, catch all unmatched routes */ }
    <Route component={NotFound} />
  </Switch>
)

和 AuthenticatedRoute 模块,如:

import React from "react";
import { Route, Redirect } from "react-router-dom";

export default ({ component: C, props: cProps, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      cProps.isAuthenticated
        ? <C {...props} {...cProps} />
        : (
          <Redirect
            to="/login"
          />
)}
  />
)

现在,一切正常,但是,当我在/books路线上并点击浏览器或 上的重新加载按钮时F5,整个应用程序会刷新,并从主页开始,我失去了当前的活动路线。

重新加载时如何保留我的活动路线?

标签: reactjsreact-router

解决方案


推荐阅读