使用React-Redux使用Axios进行用户身份验证

时间:2018-07-01 22:55:19

标签: reactjs redux

在开发我的Web应用程序时,我试图过渡到redux。

我意识到,在actions中指定类型之后,可以将其分派到reducersreducers将根据{{1}的类型进行更改}。

我有两个actions,看起来像这样:

actions

我可以将这两个动作分派给我的export const doLogin = (username, password) => { return { type: types.AUTH_LOGIN, username, password }; }; export const doLogout = () => ({ type: types.AUTH_LOGOUT, }); ,如下所示:

reducer

我的const initialState = { username: "", isLoggedIn: false }; const authReducer = (state = initialState, action) => { switch (action.type) { case types.AUTH_LOGIN: return { ...state, // Preserve states that are unchanged username: action.username, // Values to be changed isLoggedIn: true }; case types.AUTH_LOGOUT: return initialState; default: return state; } }; 当前仅创建一个新状态reducer并返回它。它与实际的用户身份验证无关。

在切换到username: username, isLoggedin: true之前,我通过使用Redux调用API Post进行了用户身份验证。

代码如下:

Axios

我不确定必须如何将其合并到 axios.post('http://localhost:5000/signin', { username:this.state.username, password:this.state.password }) .then(function (response) { console.log(response); if(response.data.status === "Successful"){ console.log("Login successfull"); this.setState({loggedOn:true}) } else{ console.log("There is no user with the given username and password"); //alert("Username does not exist"); } } ) .catch(function (error) { console.log(error); }); 中。我是否必须将其放入我的Reduxreducers中?

请帮助。

编辑

我已经在使用actions

store.js

redux-thunk

index.js

import rootReducer from "../reducers";
import ReduxThunk from "redux-thunk";

const middlewares = [ReduxThunk];
const store = createStore(rootReducer, applyMiddleware(...middlewares));

import store from "./store"; import { createStore } from 'redux'; import reducers from './reducers'; import { Provider } from 'react-redux'; console.log('init state', store.getState()); store.subscribe(()=>console.log(store.getState())); store.dispatch(actions.doLogin('sample', '1234')); 给我错误actions.doLogin

2 个答案:

答案 0 :(得分:3)

我使用如下的调度功能

export const doLogin = (username, password) => {
    return dispatch => {
        axios.post('http://localhost:5000/signin', {
            username: username,
            password: password
        })
        .then((response)=>{
            dispatch({
                type: AUTH_LOGIN,
                username: response.username
            })
        })
        .catch((error)=>{
            console.log("There is no user with the given username and password");
            //alert("Username does not exist");
        })
    };
};

答案 1 :(得分:1)

Reducer仅接收状态更改。因此,您的操作应包含身份验证。然后,完成操作并验证用户身份后,它将返回到reducer。像这样:

export const doLogin = (username, password) => {
     var auth = false
     axios.post('http://localhost:5000/signin', 
     {
         username:this.state.username, 
         password:this.state.password
     }).then(response => {
         console.log(response);
         if(response.data.status === "Successful"){
             console.log("Login successfull");
             auth = true;
         }
         else{
             console.log("There is no user with the given username and password");
             //alert("Username does not exist");
         }
      }).catch(function (error) {
           console.log(error);
      });
      if(auth) return {
             type: types.AUTH_LOGIN,
             username,
             password
      }
};

export const doLogout = () => ({
  type: types.AUTH_LOGOUT,
});
  

建议:这不是一个好习惯。最好保持身份验证     在脚本或组件内部。然后,当成功时,它会发出     行动到Redux。我试了几次,发现不是     最好的方法。