Reputation: 443
I started learning react and react-redux, but I cant understand how the components or containers know about state changing and to re-render then. I tried a simple Example but cant get it to work the way it should. What I'm trying to do is to have a Counter shown and a button. Every time the button is clicked the counter should increment. Button-click dispatches an action and the state is changed, but somehow the counter is not shown on the screen. Its not even shown the initial State with the 0 counter. I'm also very new to frontend development so maybe it hasnt something to do with redux but with react.
Here is my index.js
import store from "./store/configureStore"
render(
<Provider store={store}>
<Countercont></Countercont>
</Provider>
, document.getElementById('root'));
configureStore.js
import {combineReducers, createStore} from 'redux'
import counterReducer from "./modules/counter"
const reducer = combineReducers({
tmp: counterReducer });
const configureStore = createStore(reducer)
export default configureStore;
Mycounter.js
const Mycounter = ({counter, inc}) => (
<div>
<p>"counter"</p>
<p>{counter}</p>
<Button onClick={inc}>Inc</Button>
</div>
)
export default Mycounter
countercont.js the container component
const Countercont = ({counter, inc}) => {
return (
<div>
<Mycounter counter={counter} inc={inc}/>
</div>
)
}
const mapStateToProps = state => {
return {counter: state.counter};
};
const mapDispatchToProps = dispatch => {
return {inc: () => dispatch(inc())}
};
export default connect(mapStateToProps, mapDispatchToProps)(Countercont);
counter.js the action and reducer
export default function reducer(state = {counter: 0}, action) {
console.log(state) //-> shows the correct state
switch (action.type) {
case "c":
console.log("Inc")
return {...state, counter: state.counter + 1}
default:
return state
}
}
export function inc() {
return {type: "c"}
}
Upvotes: 1
Views: 42
Reputation: 22875
Your counter state defined inside counterReducer
which is registered against tmp
key
const reducer = combineReducers({
tmp: counterReducer
});
So in order to get that value your component mapStateToProps
callback shoudl get this value from whole state using your reducer key which is tmp
in your code
So it should be like
const mapStateToProps = state => {
return {counter: state.tmp.counter};
};
instead of
const mapStateToProps = state => {
return {counter: state.counter};
};
Upvotes: 5