【问题标题】:dispatch is not a function TypeErrordispatch 不是一个函数 TypeError
【发布时间】:2017-06-12 17:27:40
【问题描述】:

我是 react-redux 的新手,我正在使用 react-thunk 中间件。每当我尝试运行我的动作创建器(通过按下我的按钮)时,我都会收到错误“Uncaught TypeError:dispatch is not a function”。有谁知道怎么回事?

src/actions/index.js

function editUserName (newUserName) {
    return {
        type: 'CHANGE_USER_NAME',
        newUserName: newUserName
    }
}

export function editUserNameDelegate () {
    return function (dispatch, getState) {
        return dispatch(editUserName("thunkUser"))
    }
}

src/containers/admin.js

import { editUserNameDelegate } from '../actions/index'
...
<input type="button" onClick={ editUserNameDelegate() } value="edit UserName" />

【问题讨论】:

  • return function (dispatch, getState) { return dispatch(editUserName("thunkUser")) } 在此函数中,您将 dispatch 作为参数,在第二行中将其视为函数???

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

商店提供dispatch 功能。因此,您要么需要使用 react-redux (https://github.com/reactjs/react-redux) 中的 connect 之类的东西将组件连接到商店,要么需要调用 store.dispatch(editUserNameDelegate())

您还需要确保已在商店中添加了 redux-thunk 作为中间件。在此处查看有关 redux-thunk 的更多信息:https://github.com/gaearon/redux-thunk

【讨论】:

    【解决方案2】:

    您正在render 内部执行editUserNameDelegate 函数,而不是将其作为onClick 处理程序传递。你想要onClick={editUserNameDelegate}

    另外,如果你是这样写的,你需要确保函数在你调用它时被绑定到调度。你可以这样做:

    export default connect(null, {editUserNameDelegate})(MyComponent)

    然后在你的渲染函数中传递onClick={this.props.editUserNameDelegate}

    【讨论】:

      【解决方案3】:

      你应该提供什么是 src/containers/admin.js 函数或类?

      如果是函数组件你应该使用onClick={() =&gt; editUserNameDelegate()}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2017-04-30
        • 2017-06-09
        • 1970-01-01
        • 2018-12-21
        • 2018-01-06
        • 2016-12-19
        相关资源
        最近更新 更多