This article mainly introduces the use of reactnative in the Redux architecture summary, small series feel very good, and now share to everyone, but also for everyone to do a reference. For. NET interested friends follow the small part to see it
This article introduces a summary of the use of Redux architecture in reactnative and shares it to everyone. Specific as follows:
It's been a while to use redux. Sum up.
Why use redux?
Background:
RN's state (variable, sub-component not visible) and props (immutable, sub-component visible) design, in the face of large projects, it is easy to inadvertently modify states cause confusion, component rendering error
RN uses the virtual DOM and does not require the target binding->action to modify UI properties, as long as the state changes, render the component in the new state, the data is passed one way, while the MVC design pattern has bidirectional data flow.
RN is not easy to test, Redux provides a very convenient way to mock test.
Redux Development
Development environment
Install redux: ' NPM install–save redux '
Installing the react native and Redux bindings Library: NPM Install–save React-redux
Installing Redux thunk Asynchronous Action middleware: NPM install–save redux-thunk
Three Principles
Single Data source
The state of the entire application is stored in an object tree, and the object tree exists in the unique store. The state in the store is bound to a component
State is read-only
The only way to change state is to trigger an action. The action is an ordinary JS object that contains the type attribute, and the type can represent the event with a constant.
Using pure functions to perform modifications
Write reducers to describe how the corresponding action modifies state. Generally can be handled with switch (action.type), no side effects
Use
The React-redux provides connect and provider.
1.Provider is the top-level distribution point, and the property is the store, which distributes the state to all the components that are connect
2.connect: Accepts two parameters: one is Mapstatetoprops or mapdispatchtoprops, and the other is the component itself to be bound.
Store
Store is the object that links Reducer with action. The Store has the following responsibilities:
Maintain a state– similar database for the application, storing all the state of the application.
Provides the GetState () method. Gets all the current state;
The dispatch (Action) method is provided to update the State, which is equivalent to storing the database and storing the action to change state.
Register the Listener with subscribe (listener).
The store is essentially an object that preserves the state of the entire application in the form of a tree. and provides a number of methods. such as GetState () and dispatch ().
The Redux app has only one by one stores.
The store is created by the CreateStore method, based on the initial state of the root reducer of the entire application.
The code is as follows:
Import {createstore, applymiddleware} from ' Redux '; import thunk from ' redux-thunk ';//asynchronous Import reducers from './reducers ' ; Const STORE = Applymiddleware (thunk) (CreateStore) (reducers); export default store;
Reducers
The action simply describes the fact that something has happened and does not indicate how the app updates the state. This is what reducer is going to do.
The essence of reducer is a function, and it is a pure function. Without any side effects. In short, reducer is only responsible for doing one thing, which is to modify the state in the store based on the received action and State:
(state, action) = NewState
When implemented in general, use switch (action.type) to determine the different action,default as the old state. You can also define the initial state.
Code:
Import {combinereducers} from ' redux '; const NewState = (state = {}, action = {}) + {switch (action.type) {case Actiontypes.cstate: return {... action.state}; Case ' _dpdatachange_ ': return {... action.dpstate}; Default: return state;}};/ /reducer Merge Export default combinereducers ({newstate,});
Note: The new state is returned, if you need to preserve some of the old state values, use the ... state (ES7 object expansion syntax, the object is shallow copy the corresponding property, here is equivalent to Object.assign ({}, State, newstate)), Merging the state will only merge one layer, and the complex state needs to be merged manually.
Action
The action is an ordinary JS object that includes at least one type attribute representing the event, and other properties that can be used to pass the data. In practice, a function is defined for a process, which can include a network request and finally return an action, which is called action Creator.
Code: Store can dispatch this action,action type represents an identifier, state is the data it carries.
Export Const NewState = state = + {Store.dispatch ({ Type:ActionTypes.CSTATE, state ,});};
Persistence of
When the action is triggered according to its reducer key to recover data, and then only need to distribute the action when the app starts, it is also easy to abstract into a configurable extension service, in fact, the three-party library Redux-persist has done this for us.
The code in the action can be as follows:
Export Const GetStorage = Async (Key) = {Const D = await asyncstorage.getitem (key); return Json.parse (d);}; Export Const Setstorage = (key, value) = = {Asyncstorage.setitem (key, json.stringify (value));};
Connect
Pass-provides the GetState () method. Gets all the current state
By using connect, bind the required state and action Creator to the props of your component, so that the component can invoke the action Creator through props, or render () different components according to different props.
Code:
Mapstatetoprops ({newstate}) { const VALUE = Newstate[name];//name:newstate.name return { name, }; },