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:
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
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.
RN is not easy to test. Redux provides a very convenient mock testing method.
Redux development
Development environment
Install Redux: 'npm install –save redux'
Install React Native and Redux binding libraries: npm install –save react-redux
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:
Maintain the state of the application – similar to a database, storing all the state of the application.
Provide getState() method. Obtain all current states;
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.
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 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, });
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, }); };
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 current state通过connect,绑定需要的state以及Action Creator到你的组件的props上,这样组件就可以通过props来调用Action Creator,或者根据不同props来render()不同的组件。
代码:
mapStateToProps({ newState }) { const value = newState[name];//name: newState.name return { name, }; },
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
相关推荐:
JavaScript技巧中关于react-redux中connect()方法详细解析
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!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
