React Redux连接()与Redux thunk
从react-redux使用Redux thunk与connect()
方法时遇到问题。我有以下代码:React Redux连接()与Redux thunk
function Component(props) {
return (
<button onClick={props.callback}>Click here</button>
);
}
function actionCreator() {
console.log('#1');
return dispatch => console.log('#2'); // = thunk
}
const mapDispatchToProps = dispatch => ({
callback: actionCreator
});
export const Container = connect(null, mapDispatchToProps)(Component);
当我渲染Container
组件,然后单击该按钮时,被显示在控制台中唯一的“#1”。所以'thunk'不会被执行。
当我明确地派遣actionCreator()
,它的工作:
const mapDispatchToProps = dispatch => ({
callback: dispatch => dispatch(actionCreator())
});
The Redux docs says this about mapDispatchToProps:
如果一个对象传递,它里面的每个功能将被假定为 一个终极版行动的创建者
那么为什么mapDispatchToProps不是dispatch()
我的actionCreator()
?我对React很陌生,所以也许我不明白它的意思吗?
更新
当使用bindActionCreators()
从终极版,它的工作:
const mapDispatchToProps = dispatch => {
return bindActionCreators({
callback: actionCreator
}, dispatch);
};
这是与connect()
结合actioncreators正确的方法是什么?
在您的mapDispatchToProps
中,通过将函数作为参数来覆盖dispatch
函数。因为你在做dispatch => {function}
,所以函数内部的调度现在指的是你传递给函数的参数 - 但是你不会传递任何参数给它。
callback: dispatch => dispatch(actionCreator())
//^overrides^
改成这样,它应该工作:
const mapDispatchToProps = dispatch => ({
callback:() => dispatch(actionCreator())
});
这样一来,当你调用callback()
,则dispatch
指通过dispatch
功能由mapDispatchToProps
,且动作被分派。
这是因为您的actionCreator
函数在被调用时会返回一个新函数。删除actionCreator
中的return
将使其工作。
感谢您的回答。它不起作用。是不是以定义thunk的方式返回函数? –
@ Jan-PaulKleemans你能提供一个jsfiddle吗?所以我可以帮你。 – geniuscarrier
我发现bindActionCreators()现在可以工作。谢谢你的帮助。 –
感谢您的回答。我已经将redux-thunk作为中间件加入了我的商店。你的代码不起作用。它在组件装入时直接分派actionCreator。当我然后单击按钮我得到错误“this.props.callback不是一个函数” –
你是对的,我现在发现真正的问题。改变'mapDispatchToProps'函数为 'const mapDispatchToProps = dispatch =>({callback:()=> dispatch(actionCreator())});' 它应该可以工作。我已经编辑了我的答案,以反映并解释为什么这是必要的! – mxstbr
再次感谢。问题在于'callback:dispatch => dispatch(actionCreator())'确实有效。但是,传递给'callback()'(从组件)的params不会被传入'actionCreator()'中。我发现'bindActionCreators()'现在工作。 –