Reputation: 23
I started using redux and just to test things out i started using combineReducers for more structured approach of designing things out ,but it doesn't work the same as everyone suggested.I have been scratching my head out that what's wrong in my approach as i followed every points that's on their official website.
index.js
import React from 'react';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reducer from './reducer';
import Welcome from './Components/Welcome';
const store=createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
<Welcome/>
</Provider>,
document.getElementById('root')
);
Welcome.js file
import React from 'react'
import {connect} from 'react-redux';
import {FIRST} from '../Actions';
function Welcome({count,dispatch}) {
dispatch({type:FIRST});
return (
<div>
<h1> Wow it's great {count}</h1>
</div>
)
}
const mapStateToProps=(store) =>({
count:store.count
})
export default connect(mapStateToProps)(Welcome);
loginsearch.js
import {FIRST} from './Actions';
const initialstore={
count:1,
total:1
}
function loginreducer(state=initialstore,action)
{
if(action.type === FIRST)
{
return{...state,count:0};
}
return state;
}
export default loginreducer;
searchreducer.js
const initialstore={
item:1,
search:1
}
function searchreducer(state=initialstore,action)
{
return state;
}
export default searchreducer;
reducer.js
import {combineReducers} from 'redux';
import loginreducer from './loginreducer';
import searchreducer from './searchreducer';
export default combineReducers({
loginreducer,
searchreducer
})
and when i console.log(count)
in Welcome.js after dispatch({type:FIRST})
i get undefined ,however in application i should get Wow it's great 0
Upvotes: 0
Views: 44
Reputation:
The problem is, you combined the reducers, but when calling the state from mapStateToProps, you forgot to add which reducer you are actually referring, so you get undefined.
I added keys to your reducers, so it can be much easier to call outside. And updated the mapStateToProps
Here is the example to fix your issue,
/*reducer.js*/
import {combineReducers} from 'redux';
import loginreducer from './loginreducer';
import searchreducer from './searchreducer';
export default combineReducers({
lr: loginreducer, // <== Check this line
sr: searchreducer // <== Check this line
})
/*welcome.js*/
const mapStateToProps=(store) =>({
count:store.lr.count, // <== Check this line
})
export default connect(mapStateToProps)(Welcome);
Upvotes: 1