简体   繁体   中英

How does action-reducer chain work in react-redux

So I have been looking into https://codesandbox.io/s/9on71rvnyo to understand how Redux works. I got to the part components/VisibilityFilters.js . I see on setFilter(currentFilter) , what calls an action in redux/actions.js . But for me the understanding stops here. I don't understand how this action connects with the reducers. This just an function call!? Does

export default connect(
  mapStateToProps,
  { setFilter }
)(VisibilityFilters);

do all the magic?

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 from getState() 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:

  1. 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.

  2. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM