如何在React应用程序中通过Redux处理登录错误

时间:2018-12-16 12:31:49

标签: reactjs react-redux

我正在学习React-Redux,并试图通过各种方式实现它来使它更舒适。我有一个登录表单,如果用户名/密码无效,我想在其中显示错误消息。我已使用所需的用户详细信息创建了配置文件。我正在调用身份验证api为登录的用户生成JWT令牌,因此,作为身份验证api的响应而获得的令牌将具有已登录的用户详细信息。我已经做了类似下面的操作,但是我每次尝试提供任何随机/错误的用户名时都能够成功登录,并且无法显示任何错误消息。我已经注释掉了componetWillreceiveProps函数,但是想了解我做错了什么。

我的Comp-

登录
import React from "react";
import Header from "./header";
import Footer from "./footer";
import { connect } from "react-redux";
import { createLogIn, setAuthError } from "../actions/action";

const axios = require("axios");
import jwtdata from "../config/jwtdata";

class Login extends React.Component {
  constructor() {
    super();
    this.state = {
      account: { user: "", password: "" }
    };
  }

  handleAccountChange = ({ target: input }) => {
    const account = { ...this.state.account };
    account[input.name] = input.value;
    this.setState({ account });
  };

  handleLoginForm = e => {
    e.preventDefault();
    let postLoginData = {};
    const userName = this.state.account.user;

    // call to action
    this.props.dispatch(createLogIn(postLoginData, userName));
    this.props.dispatch(setAuthError())

    this.props.history.push("/intro");
  };

  // componentWillReceiveProps(nextProps) {
  //   if (nextProps.authStatus){
  //     this.props.history.push("/intro");
  //   }
  // }
  render() {
    const { account } = this.state;
    return (
      <div className="intro">
        <Header />
        <form onSubmit={this.handleLoginForm}>
          <div className="content container">
            <div className="profile" />
            <div className="row">
              <div className="col-xs-12">
                <input
                  type="text"
                  autoFocus
                  placeholder="username"
                  name="user"
                  value={account.user}
                  onChange={this.handleAccountChange}
                />
                <input
                  type="password"
                  placeholder="password"
                  name="password"
                  value={account.password}
                  onChange={this.handleAccountChange}
                />
                <button
                  className={
                    "loginButton " +
                    (account.user && account.password
                      ? "not-disabled"
                      : "disabled")
                  }
                  disabled={!account.user && !account.password ? true : false}
                >
                  <span>Sign in</span>
                </button>
              </div>
              {!this.props.authStatus ? (
                <p className="login-error">
                  Authorization Failed. Please try again!
                </p>
              ) : (
                <p />
              )}
            </div>
          </div>
        </form>
        <Footer />
      </div>
    );
  }
}

const mapStateToProps = state => ({
  authStatus: state.root.authStatus
});

export default connect(mapStateToProps)(Login);

动作创建者-

export const createLogIn = (postLoginData, userName)  => (dispatch) => {

  console.log('>>> ', userName);

  console.log('authenticating');  
  console.log(btoa(JSON.stringify(jwtdata)));

  localStorage.setItem("UserData", btoa(JSON.stringify(jwtdata[userName])))
    // dispatch({
    //   type: SET_AUTH_ERROR,
    //   payload: false
    // })
    axios({
        method: "POST",
        url: "/authenticateUrl",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: postLoginData
      })
        .then (response => {
          dispatch({
            type: API_LOG_IN, 
            payload: response.data
          })
          localStorage.setItem('AccessToken', response.data.jwt_token);
        })
        .catch( error => {
          console.log("in catch block");
        });
}

export const setAuthError = ()  => {
    console.log('inside actions');
    return {
        type: SET_AUTH_ERROR, 
        payload: "Authorization Error"
    }
} 

Reducer-

const initialState = {
    authStatus: true
}
const reducerFunc = (state = initialState, action)  => {
    switch (action.type) {
        case API_LOG_IN:
        console.log('reducers');
        return {...state, logIn: action.payload}

        case SET_AUTH_ERROR:
        console.log('inside Auth reduccer');
        return {...state,authStatus: action.payload}
        default: return {...state}
    }
}

export default reducerFunc;

我正在尝试在componentWillReceiveProps中添加一个检查,但这似乎不起作用。相反,即使用户名与配置文件相同,它也总是向我显示错误消息。我想要的是显示一些消息如果我尝试使用错误的用户凭据点击登录按钮,则为“授权失败”。

1 个答案:

答案 0 :(得分:0)

zsh

似乎这行是问题所在。由于您的authStatus在未发生错误时或为“身份验证失败”时为“未定义”。