【问题标题】:Redux Thunk Middleware not workingRedux Thunk 中间件不工作
【发布时间】:2017-08-23 23:54:16
【问题描述】:

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

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

然后在我的操作中我映射到用于登录的处理程序的道具...

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
      };
    });
}

然而,有了这一切,我得到了错误 Actions must be plain objects。使用自定义中间件进行异步操作。

关于为什么的任何想法?我正在使用 thunk 中间件,逻辑似乎是正确的。

【问题讨论】:

  • 尝试检查您对登录路由的响应与减速器状态是否匹配

标签: javascript reactjs redux redux-thunk


【解决方案1】:

你需要从你的动作创建者那里返回一个函数:

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

您可以为此使用简写语法:

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

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

【讨论】:

  • 有趣。我让它与你的输入一起工作,但我想知道这是否是实现这种逻辑的最佳方式。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2020-11-29
  • 2018-10-14
  • 2016-10-18
  • 2018-03-20
相关资源
最近更新 更多