reactjs - React Router v4 - 在应用程序内重新加载页面时重定向到主页
问题描述
当用户刷新我的应用程序中的其他页面时,我需要重定向到主页。我正在使用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>
推荐阅读
- python - 如何沿行压缩或堆叠熊猫数据框?
- r - R中的日期列排序
- java - 如何参考我的代码使用扫描仪阅读器严格允许一个字符作为输入?
- java - 将 AWS Lambda handleRequest 中的输入解析为 POJO
- ios - 如何暂停 XCUITest 以进行手动模拟器操作?
- regex - 正则表达式:从句子中排除一个单词
- java - CircleCI 和在插件 org.apache.maven.plugins:maven-dependency-plugin:3.0.2 中找不到目标'go'
- r - 使用迭代将数组重塑为数据框
- django - 如何在 Google Cloud AppEngine 上为 Django 配置 Memcache?
- c++ - Zlib 通货膨胀流未在 PNG IDAT 数据末尾设置为 Z_STREAM_END