React Router v4 - 在应用程序内重新加载页面时重定向到主页

Vis*_*ati 5 reactjs react-router redux react-redux react-router-v4

当用户刷新我的应用程序中的其他页面时,我需要重定向到主页。我正在使用React routerv4 和redux. 由于商店在重新加载时丢失,用户重新加载的页面现在是空的,因此我想将他带回不需要任何先前存储数据的页面。我不想在localStorage.

我试图在事件中处理此问题,onload但没有奏效:

window.onload = function() {
    window.location.path = '/aaaa/' + getCurrentConfig();
};
Run Code Online (Sandbox Code Playgroud)

Mur*_*ati 6

您可以尝试创建一个新的路由组件,例如RefreshRoute检查您需要的任何状态数据。如果数据可用,则渲染组件,否则重定向到主路由。

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

const RefreshRoute = ({ component: Component, isDataAvailable, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      isDataAvailable ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/home"
          }}
        />
      )
    }
  />
);

const mapStateToProps = state => ({
  isDataAvailable: state.reducer.isDataAvailable
});

export default connect(mapStateToProps)(RefreshRoute);  
Run Code Online (Sandbox Code Playgroud)

现在,用这个RefreshRouteBrowserRouter像正常的Route

<BrowserRouter>
  <Switch>
    <Route exact path="/home" component={Home} />
    <RefreshRoute exact path="dashboard" component={Dashboard} />
    <RefreshRoute exact path="/profile" component={ProfileComponent} />
  </Switch>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)


Ame*_*icA 0

令人惊奇的是,您不想在浏览器中保留用户路线图的状态,但您使用了react-router!,您的情况的主要解决方案是不使用react-router

如果您不使用它,则每次refresh应用程序都会返回应用程序的主视图,如果您想在address bar没有任何反应的情况下查看路线图,请使用JavaScript history pushState

希望对您有帮助。