Open Akiq2016 opened 6 years ago
For example, React. React bindings for Redux embrace the idea of separating presentational and container components.
-- | Presentational Components | Container Components |
---|---|---|
Purpose | How things look (markup, styles) | How things work (data fetching, state updates) |
Aware of Redux | No | Yes |
To read data | Read data from props | Subscribe to Redux state |
To change data | Invoke callbacks from props | Dispatch Redux actions |
Are written | By hand | Usually generated by React Redux |
Most of the components we'll write will be presentational, but we'll need to generate a few container components to connect them to the Redux store. Technically you could write the container components by hand using store.subscribe()
. But React Redux makes many performance optimizations that are hard to do by hand. So we'd be better to use the connect() function provided by React Redux.
tutorial
Actions
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using
store.dispatch()
.Action creators are exactly that—functions that create actions. In Redux, action creators simply return an action:
Reducers
Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe the fact that something happened, but don't describe how the application's state changes.
As a pure function, here's are things you should never do inside a reducer:
That's said, given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.
For example:
Object.assign()
. You can also enable the object spread operator proposal to write{ ...state, ...newState }
instead.while your app grows more complex, you'll want to split your reducing function into separate functions, each managing independent parts of the state. The combineReducers helper function can turn an object whose values are different reducing functions into a single reducing function you can pass to createStore.
Store
You'll only have a single store in a Redux application. The store has the following responsibilities:
getState()
;dispatch(action)
;subscribe(listener)
;subscribe(listener)
.Demo1
Having the above knowledge, a simple store's update logic can be like this: