Redux officially defines it as a predictable state container for JavaScript applications. That is, when we give a value, the result for that value is predictable.
Redux provides a unique API called createStore(). This is literally a way to create a store.
For store, it has four key points:
-
State is the State value in the store, which can only be obtained by getState()
-
GetState is a method specifically used to getState
-
Dispatch is used to Dispatch methods to change state
-
Subscribe The method used to Subscribe to a state
Next, let’s use graphical form to parse the process.
A quick overview of the Redux workflow.
The View layer submits an action through dispatch, and then finds the reducer successfully matched with the action in reducers. The state in store is modified by reducer. The view layer is then modified with subscribe.
These simple sentences summarize several features of Redux:
-
Redux is a one-way data flow
-
Redux acts as a middleware
With that in mind, let’s take a look at the all-too-familiar counter demo.
Import React,{useState,useEffect} from "React" import {createStore} from "redux" ------- first step let reducers = (state=0,action)=>{ switch (action.type) { case "increment": return state + 1; case "decrement": return state - 1; default: return state; }} ------ step 2 Let Store = createStore(reducers) ------ Step 3 Let add = () => {store.dispatch({type:"increment"})} let Minus = () => {store.dispatch({type:"decrement"})} function App(props){----- useState({num:0}) useEffect(()=>{ store.subscribe(()=>{ setCount({num:store.getState()}) }) }) return ( <div> hello World < h3 > {count. Num} < / h3 > button onClick = {() = > {the add ()}} > add < / button > < br / > < br / > < button The onClick = {() = > {minus ()}} > minus < / button > < / div >)} export the default AppCopy the code
I looked at the counter demo above. There are a few hooks to emphasize, after all, with other people’s things, the rules inside or need to understand.
-
The Reducer definition must carry two necessary parameters, state and the action to modify state
-
Actions must be dispatched with dispatch
-
For the view layer, subscribe to the state, which changes the view layer whenever the state changes
Above, learn to waste?