React summarized notes: Quick Start One acquaintance Redux

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/u012149969/article/details/90298736

How to build reusable components view has been React concern. But if you want to develop a large-scale web applications, use only React is a very painful thing. Because alone solve the data transfer between the components and state management enough for you to drink a pot of! The library --Redux to you recommended a force that can help us be more efficient and clearly the state of applications and components to manage!

Introduction Redux

With the demand for single-page applications become more complex, you need to manage the state more and more. Here state that is data, which includes not only the data obtained from the server, the data also includes the creation of local, state, and data reflecting the UI.

Redux reasonable agreement through a series of steps to modify the application specification standardized, centralized, so that no complex, becomes clearer and cute.

With official website sentence describes Redux: Redux is a predictable state management container of JavaScript.

Translation adult words to say: Redux is a container for storing JavaScript state, as long as you put the container in the state, the program you write will be consistent behavior and easy to test! All in all, a cow on the right.


There are three main components Redux part: action, reducer, store.

Redux Configuration

We quickly build a Redux environment through the create-react-app.
1, create a my-app application:

create-react-app zhangpeiyue

2, installation redux

cnpm install redux --save

Into the project, open the src folder, all files except index.js delete all! Since the whole world is quiet!

store (warehouse storage state)

Open index.js, the code can all kill! Then write the following code:

// 引入createStore方法
import {createStore} from "redux";

// 初始化数据状态
const initState={
    userName:"ZhangPeiYue",
    age:16
}

// 第一个参数state是你保存在store中的数据。
// 第二个参数action是操作state的行为,后面再做介绍
const reducer = function(state=initState,action){
    return state;
}

// 通过createStore方法创建store
const store=createStore(reducer);
// 通过store的getState方法取得状态
const myState=store.getState();
console.log(myState.userName)// ZhangPeiYue
console.log(myState.age)// 16

Explain the above code:
. 1, State is the state of the application, and refers to a state store warehouse. You can also be understood as the application of state of the state store managers.
2, the relationship between the state and store: state = store.getState ().
3, store by calling the createStore Redux obtained.
4, reducer is a synchronous function that is responsible for updating and returns a new state.
note:

  • store is a single data source, only one Store

Action (action)

So far, we just created a store, and put the state in the store memory, and finally through store.getState () to get a state. Other nothing has been done. If we want to add or modify the properties of how to do?

In accordance with the provisions of Redux, we can not directly modify the state. In other words, the following behavior is not allowed:
let myState=store.getState();
myState.userName="LaoWang";

To operate the state, action can only be distributed through a dispatch method, this is the only right path!

action is actually a containing type (mandatory) common object properties, this type is the key to determine the user's behavior.

Now we'll reducer method modified as follows:

// 第一个参数state是你保存在store中的数据。
// 第二个参数action是操作state的行为,后面再做介绍
const reducer = function(state=initState,action){
    // 后续可能会有多个action,所以此处建议使用switch对type进行判断
    switch(action.type){
        case "ADD_TO_STATE":
            return Object.assign(state,{
                sex:"男"
            })
        default:
            return state;
    }
}

By distributing a dispatch to action:

store.dispatch({
    type:"ADD_TO_STATE"
});

View the current warehouse status:

const myState=store.getState();
console.log(myState.sex);// 男

By adjusting for the above program, the success of the state increased the value of a male sex attributes.
Complete code:

// 引入createStore方法
import {createStore} from "redux";

// 初始化数据状态
const initState={
    userName:"ZhangPeiYue",
    age:16
}

// 第一个参数state是你保存在store中的数据。
// 第二个参数action是操作state的行为,后面再做介绍
const reducer = function(state=initState,action){
    // 后续可能会有多个action,所以此处建议使用switch对type进行判断
    switch(action.type){
        case "ADD_TO_STATE":
            return Object.assign(state,{
                sex:"男"
            })
        default:
            return state;
    }
}
// 通过createStore方法创建store
const store=createStore(reducer);
store.dispatch({
    type:"ADD_TO_STATE"
});
const myState=store.getState();
console.log(myState.sex);// 男

Summary:
. 1, a dispatch method in a store.
2, after the dispatch action distribution, eventually perform a function reducer
3, obtained in the second parameter reducer of action that is distributed
. 4, according to the action type attribute, determines whether the operation state


But so far, the increase in property fixed for men, if it is to control its value through action, we can modify the reducer methods:

const reducer = function(state=initState,action){
    // 后续可能会有多个action,所以此处建议使用switch对type进行判断
    switch(action.type){
        case "ADD_TO_STATE":
            return Object.assign(state,{
                sex:action.payload.sex
            })
        default:
            return state;
    }
}

Modification of the action:

store.dispatch({
    type:"ADD_TO_STATE",
    payload:{
        sex:"女"
    }
});

result:

const myState=store.getState();
console.log(myState.sex);// 女

Summary: action property of the data payload can support, enabling data transfer value.


However, there is loads of data and the action is not flexible enough, if I want to change sex even if the value of the action to write again, more trouble. So we can use a function of the factory model, according to production needs action:

function addToState(sex){
    return {
        type:"ADD_TO_STATE",
        payload:{
            sex
        }
    }
}

Implementation of dispatch, view the results:

store.dispatch(addToState("未知"));
const myState=store.getState();
console.log(myState.sex);// 未知

Complete code:

// 引入createStore方法
import {createStore} from "redux";

// 初始化数据状态
const initState={
    userName:"ZhangPeiYue",
    age:16
}

// 第一个参数state是你保存在store中的数据。
// 第二个参数action是操作state的行为,后面再做介绍
const reducer = function(state=initState,action){
    // 后续可能会有多个action,所以此处建议使用switch对type进行判断
    switch(action.type){
        case "ADD_TO_STATE":
            return Object.assign(state,{
                sex:action.payload.sex
            })
        default:
            return state;
    }
}
// 通过createStore方法创建store
const store=createStore(reducer);

function addToState(sex){
    return {
        type:"ADD_TO_STATE",
        payload:{
            sex
        }
    }
}
store.dispatch(addToState("未知"));
const myState=store.getState();
console.log(myState.sex);// 未知

Summary: Common object action is essentially generated by a function having a property type.


Now we have to reducer function should be no stranger. But note the following points:
1, and if the reducer must be synchronized with a pure function, receives state and Action
2, the user after each dispatch (action), reducer will trigger the execution of
3, reducer must have a return value, otherwise the state is undefined
4 Finally, the return value of the state completely replace the original state. He said bluntly, reducer return of what is, state what is!
----- END -----
like this article friends, welcome public attention No. Zhang Peiyue , watch for more exciting content! ! ! No public reply to e-books , e-books give you a classic!

Guess you like

Origin blog.csdn.net/u012149969/article/details/90298736