Redux Thunk 中间件不工作

Redux Thunk Middleware not working

我正在使用 Redux 实现基本登录。当我创建我的商店时,我做了以下事情:

const store = createStore(
    reducers,
    applyMiddleware(thunk)
);

然后在我的操作中,我映射到 props 登录处理程序...

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        loginRoute: (username,password) => {
            dispatch(loginRoute(username,password));
        },
        dispatch
    }
};

然后在提交时分派操作...

this.props.loginRoute(username.value,password.value); 

登录路由函数如下所示.....

export function loginRoute(username, password){
    return axios({
      method: 'post',
      url: '/login',
      data: {
        'username': username,
        'password': password
      }
    }).then((response)=>{
        if(response.data === "no username in database"){
          // send action to update state, no username in database
          return{
            type: "ERROR",
            response
          };
        }else if(response.data ==="incorrect password"){
          return{
            type: "ERROR",
            response
          };
        }else{
          return{ 
            type: 'LOGIN',
            data:response 
          };      
        }
    }).catch((error)=>{

      return{
        type: "ERROR",
        response: error
      };
    });
}

但是,对于所有这些,我得到错误操作必须是普通对象。使用自定义中间件进行异步操作。

关于原因有什么想法吗?我正在使用 thunk 中间件,逻辑似乎是正确的。

您需要 return 动作创建者的函数:

export function loginRoute(username, password) {
    return function(dispatch, getState) {
        axios({...}).then((response) => {
            ...
            dispatch({type: 'LOGIN', data: response})
        }
    }
}

您可以为此使用 shorthand 语法:

export const loginRoute = (username, password) => (dispatch, getState) => {
    ...
}

或者,您可以使用另一个中间件,它应该可以完全像上面那样实现,https://github.com/acdlite/redux-promise