从react-redux使用 connect()
方法使用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:
如果传递了一个对象,则其中的每个函数都将被假定为Redux动作创建者
那么为什么mapDispatchToProps不是 dispatch()
我的 actionCreator()
?我明白了吗?
Update
从redux使用 bindActionCreators()
时它确实有效:
const mapDispatchToProps = dispatch => {
return bindActionCreators({
callback: actionCreator
}, dispatch);
};
这是将actioncreators与 connect()
绑定的正确方法吗?
2 回答
这是因为你的
actionCreator
函数在被调用时会返回一个新函数 . 删除actionCreator
中的return
将使其正常工作 .在
mapDispatchToProps
中,通过将dispatch
函数作为函数的参数来覆盖它 . 因为你正在执行dispatch => {function}
,函数内部的调度现在引用传递给函数的参数 - 但是你没有传递任何参数 .将其更改为此,它应该工作:
这样,当你调用
callback()
时,dispatch
引用mapDispatchToProps
传递的dispatch
函数,并调度该动作 .