调度的redux操作不正确

时间:2017-10-11 04:25:28

标签: redux react-redux

我是redux的新手,并致力于应用程序。我的登录和注册功能几乎正常,除了如果调度了一些不正确的操作并且无法找到代码的哪一部分正在执行它。下面我发布一些代码片段。

看看第二个幽灵LOGIN_FULFILLED请求,它不应该发生,因为我还没有在DB中拥有该用户! Screenshot for the actions and state transitions

登录操作创建者:

import request from 'axios';
import thunk from 'redux-thunk';
import store from '../store'

export function loginFunc(username, password) {  
return {
type: 'LOGIN',
username,
password,    
payload : request
            .post("http://localhost:5000/users/authenticate", 
                { 
                  username : username, 
                  password: password 
                }
            )
            .then(function (response) {
              console.log(response);
              if (response.data.message === "user_found")                    
                store.dispatch({type: 'LOGIN_FULFILLED', payload : response.data.results});
              else 
                store.dispatch({type: 'LOGIN_REJECTED', payload : "user_not_found"});
            })
            .catch(function (error) {
              console.log(error);
              store.dispatch({type: 'LOGIN_REJECTED', payload : error});
            })
  }
}

1 个答案:

答案 0 :(得分:0)

Redux Thunk中间件允许您编写返回函数而不是操作的动作创建者(如official guide所述)。

您需要进行一些更改才能使用thunk。您无需导入store即可使用getStatedispatch,因为它们是参数 callback

return function(dispatch, getState)

dispatchgetStatestore.dispatchstore.getState相同。

import request from 'axios';

export function loginFunc(username, password) {
  return function(dispatch) {
    request
      .post("http://localhost:5000/users/authenticate", {
        username: username,
        password: password
      })
      .then(function(response) {
        console.log(response);
        if (response.data.message === "user_found")
          dispatch({
            type: 'LOGIN_FULFILLED',
            payload: response.data.results
          });
        else
          dispatch({
            type: 'LOGIN_REJECTED',
            payload: "user_not_found"
          });
      })
      .catch(function(error) {
        console.log(error);
        dispatch({
          type: 'LOGIN_REJECTED',
          payload: error
        });
      })
  }
}

相关问题