【发布时间】:2016-06-12 13:53:50
【问题描述】:
我在使用 Redux thunk 和 react-redux 中的 connect() 方法时遇到问题。我有以下代码:
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()?我是 React 新手,所以也许我不明白吗?
更新
当使用 redux 中的 bindActionCreators() 时,它确实有效:
const mapDispatchToProps = dispatch => {
return bindActionCreators({
callback: actionCreator
}, dispatch);
};
这是将 actioncreators 与 connect() 绑定的正确方法吗?
【问题讨论】:
标签: javascript reactjs redux