I have been playing around with Redux, but I can't seem to get it to connect with React. I am using connect with mapStateToProps but the props in my store are not being passed into my component. Perhaps somebody could shed some light on why my code won't work? I'm guessing it has something to do with the mapStateToProps function.
Here's the code that I've got:
import { connect, Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import React from 'react';
import ReactDOM from 'react-dom';`enter code here`
const greetReducer = ( state = '', action ) => {
if ( action.type === 'greet' ) {
state = action.greeting
}
return state;
};
const runReducer = ( state = '', action ) => {
if ( action.type === 'run' ) {
state = action.running
}
return state;
};
const reducers = combineReducers({
greetState: greetReducer,
runState: runReducer
});
const store = createStore( reducers );
store.dispatch({
type: 'greet',
greeting: 'Hello'
});
console.log(store.getState());
store.dispatch({
type: 'run',
running: 'Running like the wind'
});
const App = (props) => <h1>{props.greeting}</h1>;
const mapStateToProps = function(store) {
return {
greeting: store.getState().greetState
};
}
connect(mapStateToProps)(App);
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById('root')
);
The connect function (or, rather, the function returned by connect) does not modify your component; it returns a new component, which you need to save to a variable:
const ConnectedApp = connect(mapStateToProps)(App);
ReactDOM.render(
<Provider store={store}><ConnectedApp /></Provider>,
document.getElementById('root')
);
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