【问题标题】:Redux-thunk - dispatch is not a functionRedux-thunk - dispatch 不是一个函数
【发布时间】:2017-06-09 05:07:16
【问题描述】:

我在使用 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
      }
    }
  }
}`

ma​​pActionsToProps

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

顺便说一句,您可以看到我在 mapActionsToProps 中控制了调度函数,并且它按预期返回:

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

    return next(action);
  }

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    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 调度此操作。

    【讨论】:

    • 其实根据redux源码中的注释是This [bindActionCreators function] is just a convenience method, as you can call "store.dispatch(MyActionCreators.doSomething())" yourself just fine。除此之外,我没有看到我们的代码结构有任何真正的区别,还有其他区别吗?谢谢
    • 你是对的。我只是习惯于绑定ActionCreators。您是否尝试过从 mapActionsToProps 返回您的函数?
    • const mapDispatchToProps = dispatch => { return { signUp: (data) => { dispatch(userActions.signUp(data)) } } }
    • 是的,我只是用了另一种写法,但实际上我就是这样写的。
    猜你喜欢
    • 2017-04-30
    • 2017-10-31
    • 2021-04-26
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2019-07-19
    • 2019-01-27
    • 2020-07-21
    相关资源
    最近更新 更多