note
Defining a store (createStore)
import { createStore } from 'redux';
function reducer(state = initialState, action) {
switch (action.type) {
'INCREMENT':
return {
count: state.count + 1
}
'DECREMENT':
return {
count: state.count -1
}
default:
return state;
}
}
const store = createStore(reducer);
connect
Replace direct usage of your Component with this;
import { connect } from 'react-redux';
// this function will define how the current component will use the global state
function mapStateToProps(state) {
return {
x: state.x,
}
}
class Component extends React.Component {
increment = () => {
this.props.dispatch({ type: 'INCREMENT' })
}
decrement = () => {
this.props.dispatch({ type: 'DECREMENT' })
}
render() {
return {
<div>
<button onClick={this.decrement}>-<button>
<span>{this.props.x}</span>
<button onClick={this.increment}>+</button>
</div>
}
}
}
export connect(mapStateToProps)(Component);
Provider
To do this, we need to provide the state to the whole application. Like the following
import { Provider } from 'react-redux';
...
const App = () => {
<Provider store={store}>
<Component />
</Provider>
}
store is the one from output of the createStore method.