繁体   English   中英

Redux-thunk - dispatch 不是函数

[英]Redux-thunk - dispatch is not a function

我在使用 redux-thunk 时遇到了麻烦。 它说 dispatch 不是我的动作创建者内部的函数,我尝试安慰返回的参数,但没有。

代码如下:

行动

export function signUp(data) {
  return dispatch => {
    console.log(dispatch)
    if (data.email === 'email@server.com') {
      dispatch(signIn(data, () => {
        if (data.type === '2') {
          browserHistory.push('/settings/profile')
        } else {
          browserHistory.push('/')
        }
      }))
    } else {
      return {
        type: ActionTypes.USER_SIGN_UP__ERROR
      }
    }
  }
}`

mapActionsToProps

const mapActionsToProps = dispatch => ({
  signUp (data) {
    console.log(dispatch)
    dispatch(userActions.signUp(data))
  }
})

顺便说一下,你可以看到我在 mapActionsToProps 中控制了 dispatch 函数,并且它按照预期返回:

  function (action) {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  }

Dispatch 不是函数,因为它不是从动作创建者传递的。

此外,你不应该在你的 mapActionsToProps 中调度任何动作。 你只需要绑定它们就可以被连接的组件访问。

你的 mapActionsToProps

const mapActionsToProps = (dispatch) => {
  return {
    asyncAction: bindActionCreators(asyncAction, dispatch),
  }
}

const Container = connect(mapStateToProps, mapActionsToProps)(Component);

异步操作

export const asyncAction = (email) => {
  return (dispatch, getState) => {

    const state = getState();

    dispatch(StartAsync());

    return fetch(`${apiUrl}/endpoint?email=${email}`, {
      method: 'GET'
    })
        .then(response => response.json())
        .then((result) => dispatch(finishedAsync(result)),
              (error) => dispatch(failedAsync(error)))
        .catch(e => {
          console.log('error:', e);
        });
  };
};

然后,在你连接的组件中,你可以从 props 调度这个动作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM