Reputation: 918
I am new to Redux and i am finding some problems with understanding concept of reducers, I can see many examples showing it takes current state and return updated state, My question is how it updates the Store by returning the new state ( i am finding difficult to understand the mechanism ), can some one please explain me .
Upvotes: 1
Views: 1575
Reputation: 918
Actually this is the part that i was missing about reducers,The part i didnt catch was reducers out put has to be assigned to store property
let Action={type:'SET_VISIBILITY_FILTER',text: 'test pay load'}
//Invoking Reducer
let store=todoApp({},Action)
//Reducer
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
message: action.text
})
default:
return state
}
}
Upvotes: 0
Reputation: 721
The Redux store is nothing but just an object holding all states of the application. The reducer is the only way to update the store.
The reducer is a pure function with takes an old state and returns a new state. In reducer what we need to do is that we just provide the old state which is store currently having and then the new state which we are going to change state. You can refer this for detailed explanation for reduce function.
In simple words, reducer takes existing state object updates some property passed through reducer function and returns new object state.
Following link has better explanation. This is very nice blog how to create your own redux. You will get exactly what happens in the redux store.
https://www.jamasoftware.com/blog/lets-write-redux/
Upvotes: 5
Reputation: 2528
this is image that i found very helpfull when i was learning the same concept.
When you dispatch any function it goes to all reducers and if the type of dispatch matches it will change the state of that reducer.
functionName:()=>(dispatch)({type:'some-thing-to-match',payload})
const store = combineReducers({
Reducer1:r1,
Reducer2:r2,
Reducer3:r3
})
var mapStateToProps = state=>{
return:{
r1:r1
}
}
then react will react to any change in state. If state of r1 is changed then it will update that component.
As we can see in image. Dispatch will change the store's state.Then you can import(connect) that reducer to see the changes in your component.(here TodoItem is that component)
Upvotes: 4