首页 > 解决方案 > 奇怪的错误反应 redux 让我发疯

问题描述

今天我面临一个让我发疯的错误!我正在使用 react with redux ,以前从未见过这样的错误。问题是我用 redux 分派的函数的“第二个参数”总是返回我所有的 REDUX 状态,所有其他参数都在工作并返回给我他们必须返回的东西!除了 2ND 谁总是返回所有的状态?那是什么魔法

this.props.sendPushNotification(); // even with empty parameters return the second parameters with all the redux state


const mapDispatchToProps = dispatch => ({


  sendPushNotification: dispatch.notifications.sendPushNotification,

});



// my redux function  

async sendPushNotification (token, title , body , data) {
    
    
    console.log(token) // return undefined
    
    console.log(title) // ALWAYS RETURN ALL THE STATE / PROPS FROM REDUX EVEN IF THERE IS NO PARAMETERS 

console.log(body) // return undefined
console.log(data) // return undefined
    
    
    
    }

标签: reactjsredux

解决方案


是的,您当前的mapDispatch代码非常错误。

首先,根据我们的文档,您应该使用“对象速记”形式mapDispatch而不是函数形式

const mapDispatch = {
  sendPushNotification: notifications.sendPushNotification,
}

其次,如果你写成mapDispatch一个函数,现在由你来接受dispatch传入的参数,并使用它来创建新的动作,在调用时分派:

const mapDispatch = dispatch => ({
  sendPushNotification: (...args) => dispatch(notifications.sendPushNotification(...args))
})

第三...我不知道你为什么要写dispatch.notifications.sendPushNotification。商店的dispatch方法上不应该有任何嵌套字段,所以看起来它应该是开箱即用的。

最后,至于“从传入的 Redux 商店获取所有道具”部分......我只能假设你的函数被解释为某种 thunk,因此它getState作为第二个参数传入。

但实际上,这里的问题是你的mapDispatch代码是错误的。请修复它。


推荐阅读