简体   繁体   English

dispatch 不是函数 TypeError

[英]dispatch is not a function TypeError

I'm new to react-redux and I'm using the react-thunk middleware.我是 react-redux 的新手,我正在使用 react-thunk 中间件。 I'm getting the error "Uncaught TypeError: dispatch is not a function" whenever I try to run my action creator (by pressing my button).每当我尝试运行我的动作创建者(通过按下我的按钮)时,我都会收到错误“未捕获的类型错误:调度不是函数”。 Anyone know what's going on?有谁知道这是怎么回事?

src/actions/index.js源代码/操作/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 src/容器/admin.js

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

You're executing the editUserNameDelegate function inside of render , instead of passing it as the onClick handler.您正在render内执行editUserNameDelegate函数,而不是将其作为onClick处理程序传递。 You want onClick={editUserNameDelegate} instead.你想要onClick={editUserNameDelegate}代替。

Also, if you're writing it that way, you need to make sure that the function is bound up to dispatch when you call it.此外,如果您是这样编写的,则需要确保该函数在调用时绑定到 dispatch。 You can do that like:你可以这样做:

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

And then pass onClick={this.props.editUserNameDelegate} in your render function.然后在渲染函数中传递onClick={this.props.editUserNameDelegate}

The store is what provides the dispatch function. store 提供了dispatch功能。 So you either need to connect your component to the store using something like connect from react-redux ( https://github.com/reactjs/react-redux ), or you need to call store.dispatch(editUserNameDelegate()) .因此,您要么需要使用诸如从 react-redux ( https://github.com/reactjs/react-redux ) connect东西将您的组件连接到商店,要么您需要调用store.dispatch(editUserNameDelegate())

You also need to make sure you have added redux-thunk as middleware in your store.您还需要确保在商店中添加了 redux-thunk 作为中间件。 See more about redux-thunk here: https://github.com/gaearon/redux-thunk在此处查看有关 redux-thunk 的更多信息: https : //github.com/gaearon/redux-thunk

You should provide what is src/containers/admin.js function or class?你应该提供什么是 src/containers/admin.js 函数或类?

If it is function component you should use onClick={() => editUserNameDelegate()}如果是函数组件,则应使用onClick={() => editUserNameDelegate()}

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

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