【问题标题】:React, Redux and Router authenticationReact、Redux 和路由器身份验证
【发布时间】:2020-06-11 00:22:38
【问题描述】:

不知道这是不是一个好问题。但是,我一直在寻找几个小时,我找不到我的问题令人满意的答案。为了简短起见,在我的路由器中,当我路由到 /dashboard 时;我想检查用户是否登录。如果用户没有登录,我想将他重定向到我的登录页面。唯一的问题,我从 redux 接收我的 isAuthenticated(is logged in) 变量,加载需要一秒钟。因此,每当我检查时,我的变量结果都是空的。

这是代码,

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);

非常感谢任何提供帮助的人。 react 和 redux 仍然是新手。

【问题讨论】:

  • 您每次访问仪表板时都得到正确的isAuthenticated 吗?
  • 是的。我有一个正常的 if 语句,这样我就可以运行多个东西。我看到有一次它会打印空。之后它会打印 true / false。

标签: node.js reactjs react-redux


【解决方案1】:

您可以设置您的组件defaultProps。更多信息在这里:https://reactjs.org/docs/react-component.html#defaultprops

AppRouter.defaultProps = {
  isAuthenticated: false
};

注意:React 的实验性 Suspense 组件可能对您有用,如果您希望在用户被验证时呈现加载组件。更多信息在这里:https://reactjs.org/docs/concurrent-mode-suspense.html

【讨论】:

  • 嘿烤肉。对不起,但我完全不明白你的意思。当我等待收到来自我的 redux 商店的响应时,设置默认道具将如何帮助我?我完全不明白所有这些东西,所以澄清会有所帮助!
  • 通过将isAuthenticated 的defaultProps 设置为false,您将阻止用户看到仪表板。但是,即使isAuthenticatednull,也会看到此行为。当isAuthenticated 最终解析时,组件应该更新,因为isAuthenticated 属性正在改变。您现在遇到什么问题?
猜你喜欢
  • 2016-12-11
  • 2021-12-20
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2017-09-24
  • 2012-10-11
  • 2018-12-19
相关资源
最近更新 更多