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

问题描述 投票:2回答:2

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

我试图在事件onload处理这个,但它不起作用:

window.onload = function() {
    window.location.path = '/aaaa/' + getCurrentConfig();
};
reactjs redux react-router react-redux react-router-v4
2个回答
2
投票

你可以尝试创建一个新的路由组件,比如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中使用这个BrowserRouter就像正常的Route一样。

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

0
投票

令人惊讶的是,你不想在浏览器中保持用户路线图的状态,但你使用react-router !,你的案例的主要解决方案是不使用react-router

如果你不使用它,在每个refresh应用程序回到应用程序的主视图,如果你想看到address bar路线图没有任何反应使用JavaScript history pushState

希望它能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.