How Does Action-reducer Chain Work In React-redux
Solution 1:
The first thing is that connect()
makes a connection between your component and your Redux store. That's why you are exporting as connect(mapStateToProps, { actionName })(ComponentName);
. As the connect()
documentation states:
The
connect()
function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.
Thus from you component you are calling the function - actions - what you created which are dispatching with dispatch()
a state change. As dispatch()
documentation states:
Dispatches an action. This is the only way to trigger a state change. The store's reducing function will be called with the current
getState()
result and the given action synchronously. Its return value will be considered the next state. It will be returned fromgetState()
from now on, and the change listeners will immediately be notified.
In the reducer based on the dispatch({type: 'STRING', payload: 'your data'})
the switch
statement will find the proper type
to change the state. At the end from your reducer the returned value will be causing a rerender in your component.
With a fairly simple draw what I just made:
+1 important:
Sometimes I see that developers are missing out the return value from the reducer which causes issues. There are 2 important things to note from Handling Actions documentation:
We don't mutate the state. We create a copy with
Object.assign()
.Object.assign(state, { visibilityFilter: action.filter })
is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write{ ...state, ...newState }
instead.We return the previous state in the default case. It's important to return the previous state for any unknown action.
I hope that clarifies!
Post a Comment for "How Does Action-reducer Chain Work In React-redux"