不知道这是否是一个好问题。但是,我一直在搜索数小时,但无法为我的问题找到满意的答案。为了简短起见,当我路由到/ dashboard时,在路由器中;我想检查用户是否登录。如果用户未登录,我想将他重定向到我的登录页面。唯一的问题,我从redux接收了isAuthenticated(已登录)变量,该加载需要一秒钟。因此,每当我检查时,我的变量就会变成null。
这是代码,
import React, { Component } from "react";
import Home from "./pages/Home";
import Testimonials from "./pages/Testimonials";
import Pricing from "./pages/Pricing";
import Login from "./pages/Login";
import Register from "./pages/Register";
import DashboardHome from "./pages/Dashboard/DashboardHome";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
class AppRouter extends Component {
static propTypes = {
isAuthenticated: PropTypes.bool
};
render() {
return (
<Router>
<Switch>
<Route path="/register">
<Register />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/pricing">
<Pricing />
</Route>
<Route path="/testimonials">
<Testimonials />
</Route>
<Route path="/dashboard">
this.props.isAuthenticated ?<DashboardHome /> :
<Redirect to="/login" />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
}
}
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated
});
export default connect(mapStateToProps, {})(AppRouter);
非常感谢任何帮助的人。仍然是新的反应和还原。
答案 0 :(得分:0)
您可以设置组件defaultProps
。此处更多信息:https://reactjs.org/docs/react-component.html#defaultprops
AppRouter.defaultProps = {
isAuthenticated: false
};
注意:如果您希望在验证用户身份时呈现一个加载组件,React的实验Suspense
组件可能对您很有用。此处更多信息:https://reactjs.org/docs/concurrent-mode-suspense.html