当用户刷新我的应用程序中的其他页面时,我需要重定向到主页。我正在使用React router
v4和redux
。由于商店在重新加载时丢失,因此页面用户重新加载现在为空,因此我想将他带回不需要任何先前存储数据的页面。我不想在localStorage
保留国家。
我试图在事件onload
处理这个,但它不起作用:
window.onload = function() {
window.location.path = '/aaaa/' + getCurrentConfig();
};
你可以尝试创建一个新的路由组件,比如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>
令人惊讶的是,你不想在浏览器中保持用户路线图的状态,但你使用react-router
!,你的案例的主要解决方案是不使用react-router
。
如果你不使用它,在每个refresh
应用程序回到应用程序的主视图,如果你想看到address bar
路线图没有任何反应使用JavaScript
history
pushState
。
希望它能帮到你。