简体   繁体   English

Redux - 调度未定义

[英]Redux - dispatch is undefined in action

I'm new to redux, but i have a problem that i don't understand and it can not fix it.我是 redux 的新手,但我有一个我不明白的问题,它无法解决。

The problem is, when i want to dispatch inside my action, I've got an error who said:问题是,当我想在我的动作中调度时,我遇到了一个错误,他说:

dispatch is not a function dispatch 不是 function

Yep, he is undefined and this is the point, why he is undefined?是的,他是未定义的,这就是重点,为什么他是未定义的?

export const clearError = dispatch => {
    console.log('clear error')
    console.log(dispatch)

    dispatch({
        type: 'CLEAR_ERROR'
    })
}

I call the clearError action from Main.js , maybe my initialization is not correct, but i've tried several way, like bindActionCreators ...我从Main.js调用clearError操作,也许我的初始化不正确,但我尝试了几种方法,比如bindActionCreators ...

Main.js (how i pass props and dispatch with connect) Main.js(我如何通过连接传递道具和调度)

const mapStateToProps = (state) => state
const mapDispatchToProps = {
    clearError: clearError
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Main)

I'm really confused because in other component I use two others actions made by the same way and everything it's ok...我真的很困惑,因为在其他组件中,我使用了以相同方式制作的另外两个动作,一切都很好......

I don't know if it can help you to understand the origin of the problem but i show you how i configure the store to call configureStore() in App.js.我不知道它是否可以帮助您了解问题的根源,但我向您展示了如何配置商店以在 App.js 中调用configureStore()

import {applyMiddleware, createStore} from "redux";
import thunk from 'redux-thunk';

import reducers from './reducers'

const configureStore = () => {
    const middleware = [thunk]
    return createStore(reducers, applyMiddleware(...middleware))
}

export default configureStore

I'm listening every help and advices about redux and the best way to use it !我正在听取有关 redux 的所有帮助和建议以及使用它的最佳方式!

Really thanks to you for reading ❤️真的很感谢你的阅读❤️

The issue is that you are not returning a function from your action creator with dispatch as one of the arguments:问题是您没有从您的动作创建者返回 function 并将dispatch作为 arguments 之一:

export const clearError = () => dispatch => {

Under the hood, when you pass your action creators to mapDispatchToProps, Redux "maps" that dispatch argument to your action creators, and then assigns the mapped action creators to Component properties.在后台,当您将动作创建者传递给 mapDispatchToProps 时,Redux 将分派参数“映射”给您的动作创建者,然后将映射的动作创建者分配给组件属性。
This is also why you have to call this.props.clearError() instead of just clearError() .这也是为什么你必须调用this.props.clearError()而不仅仅是clearError()的原因。

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

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