search
HomeWeb Front-endJS TutorialHow to use Redux architecture in ReactNative

This article mainly introduces the summary of the Redux architecture used in ReactNative. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor and take a look.

This article introduces a summary of the Redux architecture used in ReactNative and shares it with everyone. The details are as follows:

I have been using Redux for some time. in conclusion.

Why use Redux?

Background:

  1. RN’s state (variable, subcomponents are invisible) and The design of props (immutable, visible to sub-components), when faced with large-scale projects, can easily cause state confusion due to inadvertent modification of state, and component rendering errors

  2. RN uses Virtual DOM, which does not Target binding->Action is required to modify the UI properties. As long as the state changes, the component in the new state is rendered, and the data is transmitted in one direction, while the MVC design pattern has a two-way data flow.

  3. RN is not easy to test. Redux provides a very convenient mock testing method.

Redux development

Development environment

  1. Install Redux: 'npm install –save redux'

  2. Install React Native and Redux binding libraries: npm install –save react-redux

  3. Install Redux Thunk asynchronous Action middleware: npm install –save redux-thunk

Three principles

Single data source

for the entire application State is stored in an object tree, which exists in a unique store. The state in the store is bound to the component

State is read-only

The only way to change the state is to trigger an action. action is an ordinary JS object containing a type attribute, which can represent events as constants.

Use pure functions to perform modifications

Write reducers to describe how the corresponding action modifies state. Generally, you can use switch(action.type) to handle it without side effects

Use

react-redux provides connect and Provider.

1.Provider is the top-level distribution point, and its attribute is Store, which distributes State to all connected components.

2.connect: accepts two parameters: one is mapStateToProps or mapDispatchToProps, and the other is mapStateToProps or mapDispatchToProps. Is the component itself to be bound.

Store

Store is the object that connects Reducer and action. Store has the following responsibilities:

  1. Maintain the state of the application - similar to a database, storing all the state of the application.

  2. Provide getState() method. Obtain all current states;

  3. Provides the dispatch(action) method to update the state, which is equivalent to storing it in the database and storing the action to change the state.

  4. Register the listener through subscribe(listener).

Store is essentially an object that saves the entire application's State in the form of a tree. and provides some methods. For example getState() and dispatch().

Redux application has only one Store.

Store is created through 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';//异步
import reducers from './reducers';
const Store = applyMiddleware(thunk)(createStore)(reducers);
export default Store;

Reducers

Action only describes the fact that something happened, and does not specify how the application updates state. This is what the reducer does.

The essence of Reducer is a function, and it is a pure function. There are no side effects. Simply put, 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

Generally implemented At this time, different Actions are judged through switch(action.type), and the default is the old state. The initial state can also be defined.

Code:

import { combineReducers } from 'redux';
const newState = (state = {}, action = {}) => {
 switch (action.type) {
  case ActionTypes.CSTATE:
   return { ...state, ...action.state };
  case '_DPDATACHANGE_':
   return {...state, ...action.dpState};
  default:
   return state;
 }
};
//Reducer 合并
export default combineReducers({
 newState,
});

Note: The new state is returned. If you need to retain part of the old state value, use...state (ES7 object expansion syntax, the corresponding properties of the object will be shallow copied, here Equivalent to Object.assign({}, state, newState)), and if you merge state, only one layer will be merged, and complex states need to be merged manually.

Action

Action is an ordinary JS object, including at least one type attribute representing the event, and other attributes can be used to pass data. In practice, a function is defined for a process. The process can include network requests and finally return Action. This function is called Action Creator.

Code: Store can dispatch this Action. The type of action represents the identifier, and state is the data it carries.

export const newState = state => {
 Store.dispatch({
  type: ActionTypes.CSTATE,
  state,
 });
};

Persistence

When the action is triggered, the data is restored according to its reducer key, and then the action only needs to be distributed when the application starts, which is also easily abstracted into configurable Expansion services, in fact the third-party library redux-persist has done all this for us.

The code in 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-provide the getState() method. Get all the current state

Through connect, bind the required state and Action Creator to the props of your component, so that the component can call Action Creator through props, or render() differently based on different props s component.

Code:

mapStateToProps({ newState }) {
      const value = newState[name];//name: newState.name
      return {
       name,
      };
     },

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

related articles:

How to implement hidden display in Angular

How to implement sensitive text prompts in Angular

How to implement it in Angular orderBy sorting and fuzzy query

How to get the keyCode of the keyboard in javascript

vue vuex vue-rouert permission routing (detailed tutorial)

The above is the detailed content of How to use Redux architecture in ReactNative. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft