Home Web Front-end JS Tutorial Summary of using Redux architecture in ReactNative_javascript skills

Summary of using Redux architecture in ReactNative_javascript skills

May 26, 2018 am 10:23 AM
js redux

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 MVC's 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 ActionMiddleware :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 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 the 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, one 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;
Copy after login

Reducers

Action only describes the fact that something happened, and does not specify how the application is updated. 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, the 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

In general implementation, switch(action.type) is used to judge different Actions, 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,
});
Copy after login

Note: The new state is returned. If you need to retain part of the old state value, use...state (ES7 object expansion syntax, the object will be shallow copied) Attribute, here is 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 returns 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,
 });
};
Copy after login

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));
};
Copy after login

connect

Pass-provide the getState() method. Get all current state

通过connect,绑定需要的state以及Action Creator到你的组件的props上,这样组件就可以通过props来调用Action Creator,或者根据不同props来render()不同的组件。

代码:

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

相关推荐:

如何理解 redux

JavaScript技巧中关于react-redux中connect()方法详细解析

在React中使用Redux的实例详解

The above is the detailed content of Summary of using Redux architecture in ReactNative_javascript skills. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles