代码之家  ›  专栏  ›  技术社区  ›  techie_questie

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

  •  0
  • techie_questie  · 技术社区  · 7 年前

    我正在学习react redux,并试图通过以各种方式实现事物来获得更舒适的体验。我有一个登录表单,如果用户名/密码无效,我想在其中显示一条错误消息。我已经创建了包含所需用户详细信息的配置文件。我正在调用一个authenticate api来为登录的用户生成jwt令牌。因此,作为authenticateapi的响应而获得的令牌将具有登录的用户详细信息。我已经做了如下的事情,但我看到我能够成功登录,每次我试图提供任何随机/错误的用户名时,无法显示任何错误消息。我已经注释掉了componetwillreceiveprops函数,但是我想知道我做错了什么。

    我的登录组件-

    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"
        }
    } 
    

    减速器—

    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 回复  |  直到 7 年前
        1
  •  0
  •   Shaegi    7 年前
    !this.props.authStatus ? (
    

    似乎这条线是问题所在。因为您的authStatus要么是“未定义”,要么是“身份验证失败”。

    推荐文章