I have a problem when using Redux thunk with the connect()
method from react-redux. I have the following code:
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);
When I render the Container
component and click the button, only '#1' is being displayed in the console. So the 'thunk' doesn't get executed.
When I explicitly dispatch actionCreator()
, it does work:
const mapDispatchToProps = dispatch => ({
callback: dispatch => dispatch(actionCreator())
});
The Redux docs says this about mapDispatchToProps:
If an object is passed, each function inside it will be assumed to be a Redux action creator
So why does mapDispatchToProps not dispatch()
my actionCreator()
? I'm new to React, so maybe I don't understand it right?
Update
When using bindActionCreators()
from redux it does work:
const mapDispatchToProps = dispatch => {
return bindActionCreators({
callback: actionCreator
}, dispatch);
};
Is this the correct way to bind actioncreators with connect()
?