I use react-redux to connect React with Redux store, and use "connect" API to inject "dispatch" property to the component. But the component does not receive the "dispatch" property. Here is the code to demonstrate the problem I encounter:
"use strict"
var React = require('react');
var ReactDOM = require('react-dom');
var Redux = require('redux');
var ReactRedux = require('react-redux');
var Provider = ReactRedux.Provider;
function menuManager(state = {count: 0}, action) {
switch (action.type) {
case 'ADD':
return state + 1;
case 'REMOVE':
return state - 1;
default:
return state;
}
}
let store = Redux.createStore(menuManager);
let TestLab = React.createClass({
onRemove: function(itemRemove) {
// this.props.dispatch undefined.
this.props.dispatch({type: 'REMOVE'});
},
onAdd: function() {
const { dispatch } = this.props
// this.props.dispatch undefined.
this.props.dispatch({type: 'ADD'});
},
getInitialState: function() {
return { count: 0 };
},
render: function() {
return (
<div>
<p>Total count: { this.state.count }</p>
<button type="button" onClick={this.onAdd}>Add Item</button>
</div>
);
}
});
function select(state) {
return state;
}
ReactRedux.connect(select)(TestLab);
var target = document.createElement('div');
document.body.appendChild(target);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);
When I try to call "this.props.dispatch", I get an error that "this.props.dispatch" is not defined.
You're not using the connected component, connect()
returns a new component.
TestLab = ReactRedux.connect(select)(TestLab);
ReactDOM.render(<Provider store={store}><TestLab /></Provider>, target);
You'll run in to some other issues as well, namely you're using this.state.count
instead of this.props.count
and your reducer function tries to increment or decrement on an object not the integer inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With