首页 > 解决方案 > 在 react redux 中全局存储用户数据以用于登录注销目的

问题描述

我是 react 和 redux 的新手,我只是想同时使用我正在创建一个应用程序,我需要在其中全局存储 userData 以便可以通过整个应用程序访问它。我使用 lumen 从后端返回 userData,但如何将其传递给整个应用程序组件,如标头和其他组件以管理身份验证。下面我粘贴代码,任何人都可以帮我完成这个。

单独登录组件我已经工作过,而不是在 redux 中,因为我不擅长它

import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import "./assets/vendor/fontawesome-free/css/all.min.css";
import "./assets/css/sb-admin-2.min.css";
import "bootstrap/dist/js/bootstrap.bundle.min";
import validator from "simple-react-validator";
import confData from "./../Config/Config";
const apiKey = confData.apiKey;
const apiURL = confData.apiURL;
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: false,
      email: "",
      password: "",
      uData: [],
      id: ""
    };
    this.validator = new validator(this);
  }
  componentDidMount = () => {
    document.title = "Sample | Login";
  };
  loginSubmit(e) {
    e.preventDefault();
    if (this.validator.allValid()) {
      let email = this.state.email;
      let password = this.state.password;
      var self = this;
      axios
        .post(apiURL + "auth/login", {
          email: email,
          password: password
        })
        .then(function(response) {
          console.log(response.data);
          self.isLoggedIn = true;
          self.uData = response.data;
          self.setState({
            email: self.uData.email,
            id: self.uData.id,
            isLoggedIn: true
          });
          localStorage.setItem("token", JSON.stringify(self.uData));
        })
        .catch(function(error) {
          console.log(error.response);
          this.isLoggedIn = false;
        });
    } else {
      this.validator.showMessages();
      // rerender to show messages for the first time
      this.forceUpdate();
    }
  }
  handleEmailChange(event) {
    this.setState({
      email: event.target.value
    });
  }
  handlePasswordChange(event) {
    this.setState({
      password: event.target.value
    });
  }
  render() {
    return (
      <div className="row justify-content-center">
        <div className="col-xl-10 col-lg-12 col-md-9">
          <div className="card o-hidden border-0 shadow-lg my-5">
            <div className="card-body p-0">
              <div className="row">
                <div className="col-lg-6 d-none d-lg-block"></div>
                <div className="col-lg-6">
                  <div className="p-5">
                    <div className="text-center">
                      <h1 className="h4 text-gray-900 mb-4">Welcome Back!</h1>
                      <Notifications options={{ zIndex: 200, top: "50px" }} />
                    </div>
                    <form
                      className="user"
                      onSubmit={this.loginSubmit.bind(this)}
                    >
                      <div className="form-group">
                        <input
                          type="email"
                          className="form-control form-control-user"
                          id="exampleInputEmail"
                          aria-describedby="emailHelp"
                          placeholder="Enter Email Address..."
                          onChange={this.handleEmailChange.bind(this)}
                          value={this.state.email}
                        />
                        <span style={{ color: "#ff0000" }}>
                          {this.validator.message(
                            "Email",
                            this.state.email,
                            "required|email"
                          )}
                        </span>
                      </div>
                      <div className="form-group">
                        <input
                          type="password"
                          className="form-control form-control-user"
                          id="exampleInputPassword"
                          placeholder="Password"
                          onChange={this.handlePasswordChange.bind(this)}
                          value={this.state.password}
                        />
                        <span style={{ color: "#ff0000" }}>
                          {this.validator.message(
                            "Password",
                            this.state.password,
                            "required"
                          )}
                        </span>
                      </div>
                      <button className="btn btn-primary btn-user btn-block">
                        Login
                      </button>
                      <hr />
                      <Link
                        to="#"
                        className="btn btn-google btn-user btn-block"
                      >
                        <i className="fab fa-google fa-fw"></i> Login with
                        Google
                      </Link>
                      <Link
                        to="#"
                        className="btn btn-facebook btn-user btn-block"
                      >
                        <i className="fab fa-facebook-f fa-fw"></i> Login with
                        Facebook
                      </Link>
                    </form>
                    <hr />
                    <div className="text-center">
                      <Link className="small" to="#">
                        Forgot Password?
                      </Link>
                    </div>
                    <div className="text-center">
                      <Link className="small" to="#">
                        Create an Account!
                      </Link>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

在这里,我从 lumen 获取 json 返回数据,现在我需要使用 redux 和 authe 对整个组件的数据进行身份验证和维护,enter code here并在用户登录后对页面进行身份验证。

标签: reactjslaravelreduxreact-reduxlumen

解决方案


首先检查 redux 文档,他们为新手提供了很好的示例https://redux.js.org/basics/example

用户更漂亮,2 个空格标签(而不是 8 个),https: //dev.to/sarah_chima/object-destructuring-in-es6-3fm 中的对象解构,您的代码非常不可读,永远不要使用 jquery 和 react。


推荐阅读