javascript - dispatch is not a function 类型错误

标签 javascript reactjs redux react-redux redux-thunk

我是 react-redux 的新手,我正在使用 react-thunk 中间件。每当我尝试运行我的 action creator(通过按下我的按钮)时,我都会收到错误“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" />

最佳答案

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

此外,如果您以这种方式编写它,则需要确保该函数在您调用它时绑定(bind)到分派(dispatch)。你可以这样做:

导出默认连接(null, {editUserNameDelegate})(MyComponent)

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

关于javascript - dispatch is not a function 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887069/

相关文章:

javascript - 有没有更好的方法通过类名引用 html 元素?

javascript - ajax传递数组值,如何在被调用页面上获取数组

javascript - 同构 react-router-redux syncHistory 中间件

javascript - 如何在 react 中从父组件访问子组件的子组件?

reactjs - 如何为多个API请求配置redux reducer ?

javascript - 在 React-Redux 的数组中添加一个元素

javascript - iPad Safari CSS/Javascript

javascript - 模式窗口/背景的问题

javascript - defaultProps 在 ReactJs 中有效吗

reactjs - Redux 表单验证在加载时触发(UPDATE_SYNC_ERRORS)