首页 > 解决方案 > React Router v4 - 在应用程序内重新加载页面时重定向到主页

问题描述

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

我试图在事件中处理这个,onload但它没有工作:

window.onload = function() {
    window.location.path = '/aaaa/' + getCurrentConfig();
};

标签: reactjsreduxreact-routerreact-reduxreact-router-v4

解决方案


你可以尝试创建一个新的路由组件,比如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);  

现在像平常一样在RefreshRoute你的中使用它。 BrowserRouterRoute

<BrowserRouter>
  <Switch>
    <Route exact path="/home" component={Home} />
    <RefreshRoute exact path="dashboard" component={Dashboard} />
    <RefreshRoute exact path="/profile" component={ProfileComponent} />
  </Switch>
</BrowserRouter>

推荐阅读