Iterator ReactNative asynchronous operation of the Redux Detailed ES6, Generator Generator functions and function

Redux with some time, there was still necessary to summarize the relevant knowledge about the system, after all, a good memory as bad written. Part blog update on " iterator ES6 in, Generator Generator function and function of asynchronous operation content", the basis of the content when the saga, saga will summarize the relevant knowledge points later. Step by step, this blog is a summary of the main Redux-related content, and then next going to sum up a blog under the react-redux, as well as redux-thunk, redux-saga middleware.

 

A, Redux in comparison with the iOS Notification of

Redux function and role of management is to make the State more focused, because redux all states are stored in the Store, and can go to access and modify Store stored value in the state of each module page. From this point of view, redux can solve a page state between multiple modules share of problems.

Redux framework to understand this is a relatively simple, the framework itself is relatively small, API involves very little. Although small, but small but excellent. Use is still full of handy, Road to SR. Below are a few key words and the corresponding function in Redux, complete understanding a few key words below, Redux framework will probably understand.

  • Store : literally see, Store storage, storage means, in Redux in the relevant state is stored in a Store, in the Redux Store embodiment can be regarded as a single object. And Store API provides a number of operations to these states, as follows:
    • getState : Store the method used to obtain the current value stored state.
    • subscribe (listener callback method ): used to monitor changes in the state value Store, the state value change performs the associated callback method.
    • dispatch (Action) : This method is used to modify the state value stored in Store, and Action is an ordinary object, some of which may carry some of the specific state information changes.
  • Action : I said above, the Action is an ordinary object, some of which may carry some of the specific state information changes, the parameter is used as a dispatch () method of. Played a role of the media, Action itself will carry some information, easy to modify the state.
  • Reducer : Reducer is the essence call a set of methods, and the parameters of these methods is the current State and Action, a new parameter is the object of State after being modified, that dispatch an Action executes a Reducer. Reducer and corresponding method, the object will be modified State Action The information carried in, the State object and returns the modified out. Of course, this return will be updated to the new State Store, which will trigger a series of listening operations.

Although Redux mode of operation is to manage the state, but feels more like to use on a personal notification. Notification and iOS in the works that is similar to the below do some simple analogy. Beneath the simple analogy drew a map, you can look up from the bottom, explained as follows:

  • Notification Center : at the bottom is the notification center, corresponding NotificationCenter iOS, mainly used to register, distribute and remove the notification, so the notification will have been NotificationCenter management. In Redux, this Store will play the role of this NotificationCenter used to manage all of the state. When different, Store stored in various states.
  • Send notice: If you want to modify the value of the state, then have to call dispatch Store provided (event-dispatching) method to modify the relevant state, if the Post method to send notifications in iOS.
  • Sign Monitor: The method Store in subscribe listener status change, similar to Notification of the register method, only add related objects finished listening to receive notification of status changes.
  • Notification target : Action Store parameters in dispatch () method, similar to Notification objects, used to carry information notification or status changes.
  • Execution method: the redux Reducer is similar in execution notification Selector for modified state.

 

Second, by way of example and subtraction term use of Redux

Below by a simple addition and subtraction procedures look Redux of use. Before responsive framework introduced in iOS ReactiveCocoa wrote a similar Demo time, but today we use Redux to achieve it.

demo is relatively simple, two addition and subtraction is automatically modified when the calculation result of the input value. Below we have to simply look at how to use Redux RN to implement this function.

 

1. Create a Store  

First create Store, redux specializes in providing a method createStore create a store, call the  createStore , we need to modify the State's method Reducer pass into the association. CalculateReducer below is a modification from the method definition of State, will be introduced later. Below the code is relatively simple, it is to create a Store, and guide the object out.  

 

 

 

 

2. Create Action

After you create Store, then we create a corresponding Action, below is the content of the code corresponding action file. First we create a CountActionType  objects, functions similar to enumerate which "ADD" represents the addition type, "DESC" represents the subtraction type. Because the sample is processed in a two Action Reducer, the so determined starting CountActionType type which is distributed by Action, and then do the corresponding operation.

AddTowNumbers then create a method that receives a parameter and returns an Action object, wherein the object type Action is ADD. DescTowNumbers the method also returns a downward Action, Action corresponding to the subtraction operation. Later we will use to the Action.

 

3. Create Reducer

calculateReducer method below is Reducer we created, which accepts two arguments, a State subject, is a Action object. Our object is assigned to the State a default value, this default value has two values, one is a addResult result of the addition, and the other is a descResult subtraction results.

Action object payload object has two values, and firstNumberhe and secondNumber, showing two input values. In Reducer by the Action Type field is done to determine the addition or subtraction operation. If the operation is an addition Add is the payload of the two values ​​are added, then the result is assigned to the state addResult. If this is the case Desc, and Add similar, but to do it is subtraction.

Reducer In this method, returns a new back-end computing State. State after being modified, changes may be made by the process can monitor the state of the subscribe Store.

 

 

4, AddTestView implementation

定义好Store、Action、Reducer, 接下来我们就开始定义可操作的视图了。下方的AddTestView就是上面两个计算加减法的控件。下方是具体实现的说明:

在AddTestView中的构造方法中,我们调用了 store 对象中的 subscribe 方法,传入了一个回调方法,来对Store中存储的状态进行监听,然后获取state中最新的状态,然后赋值给组件对应的State对象。

 

第二段核心的代码则是dispathAction了,在输入框变化后,会根据是Add还是Desc调用下方的dispatchAction方法。如果是Add, 就会调用addTowNumber方法创建一个 加法动作对应的Action。如果是减法操作的话,则会调用 descTowNumber()方法创建一个减法对应的Action对象。然后把创建好的对象,通过store.dispatch(action) 方法派发出去。

store收到 Action后就会执行对应的 Reducer方法,然后去跟进Action提供的信息修改 Store中存储的State值。当State值被修改后,就会执行 subscriber 对应的回调方法获取最新的结果值,并赋值给组件内部的State对象进行展示。

 

 

下方AddTestView的全部代码。

// 仅仅使用redux
import React, { Component } from 'react';
import { Action } from 'redux';
import {Text, TouchableOpacity, View, StyleSheet, TextInput} from 'react-native';
import { store } from './store';
import {addTowNumbers, descTowNumbers, CountActionType} from './action';
const {
    DESC,
    ADD
} = CountActionType;

type State = {
    addResult: number,
    descResult: number
};

const styles = StyleSheet.create({
    textInput: {
        width: 60,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: 'gray'
    },
    tipText: {
    }
});

export default class AddTestView extends Component<null, State> {
    addFirstNumber: string = '0';
    addSecondNumber: string = '0';
    descFirstNumber: string = '0';
    descSecondNumber: string = '0';

    constructor (props: any) {
        super(props);
        this.state = {
            addResult: 0,
            descResult: 0
        };
        store.subscribe(() => {
            const {
                addResult,
                descResult
            } = store.getState();
            this.setState({ addResult, descResult });
        });
    }

    firstTextChange = (type) => (text) => {
        if (type === CountActionType.ADD) {
            this.addFirstNumber = text;
            this.dispathAddAction();
        } else {
            this.descFirstNumber = text;
            this.dispathDescAction();
        }
    }

    secondTextChange = (type) => (text) => {
        if (type === CountActionType.ADD) {
            this.addSecondNumber = text;
            this.dispathAddAction();
        } else {
            this.descSecondNumber = text;
            this.dispathDescAction();
        }
    }

    dispathAddAction = () => {
        const action = addTowNumbers({firstNumber: this.addFirstNumber, secondNumber: this.addSecondNumber});
        store.dispatch(action);
    }

    dispathDescAction = () => {
        const action = descTowNumbers({firstNumber: this.descFirstNumber, secondNumber: this.descSecondNumber});
        store.dispatch(action);
    }

    calculate = (type) => {
        const calculateText = type === CountActionType.ADD ? '+' : '-';
        const result = type === CountActionType.ADD ? this.state.addResult : this.state.descResult;
        return (
            <View style={{flexDirection: 'row'}}>
                <TextInput style={styles.textInput} defaultValue={'0'} onChangeText = {this.firstTextChange(type)}/>
                <Text> {calculateText} </Text>
                <TextInput style={styles.textInput} defaultValue={'0'} onChangeText = {this.secondTextChange(type)}/>
                <Text> = </Text>
                <Text>{result}</Text>
            </View>
        );
    }

    render () {
        return (
            <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                {this.calculate(CountActionType.ADD)}
                {this.calculate(CountActionType.DESC)}
            </View>
        );
    }
}
View Code

 

5、总结

介绍完相关的Demo,我们可以总结一些具体的实现流程。上述各个部分的执行过程是比较简单的,下方是具体的总结:

  • Component 也就是下边的AddTestView 是不会直接调用 Reducer 方法来修改状态的,而是像 Store 通过Dispatch来派发Action的方式向Store下发修改State的命令。
  • Store在收到 Component 派发的 Action 后会调用对应的 Reducer。
  • Reducer则根据提供的Action信息来修改对应的State的值,并返回给Store,更新。
  • Component最终通过Subscribe的方式接收到更新后的State,当然派发 Action 的 Component 与 Subscriber 对应状态的 Component 大部分情况下不是一个。

 

 

上面是根据上述示例来画的简图,下方我们可以脱离上述demo, 整理了一个图。从下图中不难看出,平时在开发时,Component一般是有多个的,而Store只有一个,这些Component都像Store派发Action修改对应的状态,并且可以通过Subscriber来监听对应状态值的改变。

而Reducer也可以是多个,建议将Reducer按照修改状态的类型或者相关的业务逻辑进行拆分,拆分成多个业务模块。修改不同的状态时,会调用不同的Reducer。

 

 

上述我们是声明定义了一个Reducer ,如果修改State的东西都写在一个方法里,难免会有些难于维护。所以一般会对Reducer进行拆分,下方是对上述Reducer拆分后的代码。当然运行效果与之前的是一样的,下方也是推荐用法。

 

虽然该Demo, 使用Redux实现会比较麻烦,使用组件内部的State完全可以实现,因为是为了窥探Redux的使用方式,所以我们就用Redux实现了该demo。但是如果是跨组件的数据交流,该方式就比较合适了。

本篇博客就先到这儿吧,虽然本篇博客介绍了Redux, 但是在开发中很少直接使用,一般会结合着其他框架及中间件使用。之前还积累了一些 react-redux, 以及redux-thunkredux-saga 的东西,下篇博客把react-redux相关的东西在总结一下,做个记录也便于自己后期翻阅。最后附上redux的文档链接,有啥问题可翻阅https://www.redux.org.cn/

Guess you like

Origin www.cnblogs.com/ludashi/p/10996209.html