Redux knowledge of a summary (one can thoroughly understand redux usage)

Redux knowledge of a summary (one can thoroughly understand redux usage)

First, what is the Redux?

Official website: Redux state of the container is JavaScript application, of providing predictable state management;

  1. Javascript applications: Javascript refers to any project built, rather than just React framework to build the project, of course, they mix with the more smoothly;
  2. Status container: react projects concentrated pulled out state in a subject tree structure store (state of the container), a project can have only one store (state of the container);
  3. Predictability: For a change of status updates are operated by a pure function, heart function is pure no matter what the parameters passed, change will not affect the value of your arguments passed; that is, each state will be in the new the old state were generated, and does not change the old state, which is predictable;

Summary: Redux is based on the framework facebooke flux scheme established, because the characteristics of the data flux flowing in one direction only (unidirectional), data flow is Model (State) -> view; Flux architecture is as follows:

Note : A project in general only one store (state container), all state projects are concentrated in store for management;

Second, why use Redux?

Talk about react, react by facebook company open source front-end framework; mainly used for building front-end interface, the front-end interface project components processing carried out, that react is an abstraction layer on solving DOM level; for a complete front end projects, this is just not enough, it is not a good solution communication between the components, only the components of the communication props realized in the form of a simple structure for assembly of the complex structure, if employed in the form props for communication, the entire project will become difficult to maintain, chaotic project structure; thus was born out of another set of solutions: Redux state management framework based Flux architecture implementation;

Redux knowledge introduction:
  1. "工欲善其事必先利其器", before the introduction Redux, the first project to build a basic react with the create-react-app scaffolding tools;

create-react-app referral link: https://github.com/facebook/create-react-app

  1. If React unfamiliar small partners can refer to the following links to learn;

react Learning Link: https://zh-hans.reactjs.org/tutorial/tutorial.html

Ready for more knowledge, we can begin our tour of the Redux; in this case to understand the pure function ;

Pure function : it refers to a parameter-dependent function only, and do not change the argument passed, is called the pure function without side effects case; code as follows:

    /**
    **案例一:函数不止依赖于函数参数
    **不属于纯函数,setName函数引用了外部变量age,
    **不符合“只依赖参数”这个条件
    **/
    var name="张三";
    var age=26;
    function setName(name){
        str="姓名:"+name+";年龄:"+age;
        return str;
    }
    setName(name);
    /**
    **案例二:改变外部环境,产生副作用
    **不属于纯函数,setName函数改变了外部变量name的
    **的,也就是影响了外部环境,产生了副作用;
    **/
    var name="张三";
    function setName(name){
        name="李四";
        console.log(name);
        return name;
    }
    setName(name);
    //纯函数来了
    var name="张三";
    function setName(name){
        var newName=name;
        newName="李四";
        return newName;
    }
    setName(name);

redux simplify learning:

1, a basic understanding of the operating mechanism redux

redux state in a state belonging to the container, used to store the corresponding data state, then the Custom Action rules, which is to store the data transmitted from the application payload. The store belongs to the only source of data. You can store.dispatch () The action spread to store. Pure functions performed reducer data state change; wherein the store is connecting them conceptualized identifier; redux specific operating mechanism as shown below:
to understand the basic operating mechanism illustrated redux. as the picture shows:

2, using the tag to achieve dynamic changes in readux

1. The basic program structure built by create-react-app, and install redux npm package (cnpm install --save redux) by yarn add redux command may be mounted, improving the basic structure of the project; illustrated as follows:
Here Insert Picture Description
2. Create function using Action create the corresponding Action, actions.js file code is as follows: (Action part)

/**redux/actions.js文件代码**/
const ADD_TAG="TAG_ADD";
const DEL_TAG="TAG_DEL";

//新增标签Action
export const addTag=(payload)=>{
  return {
    type:ADD_TAG,
    payload:payload
  }
}
//移除标签Action
export const delTag=()=>{
  return {
    type:DEL_TAG
  }
}

3. Define the initial tag data state, state.js file code is as follows: (state portion)

/**redux/state.js文件代码**/
export const InitTagState=[{
  "id":"001",
  "name":"标签一"
}];

4. Create patterns reducer pure function processor (think that it is dealing with state processors), reducer.js file as follows: (part reducer)

/**redux/reducer.js文件代码**/
import {initTagState} from "./state";
import {ADD_TAG,DEL_TAG} from "./actions";

export const TagReducer=(state=initTagState,data)=>{
  let new_arr=[];
  new_arr=[].concat(state);
  switch(data.type){
    case ADD_TAG: //新增标签
      new_arr.push(data.payload);
      return new_arr;
    case DEL_TAG: //删除标签
      new_arr.splice(0,1);
      return new_arr;
    default:
      return new_arr;
  }
}

The system architecture here redux basically completed, then we need to link them together to form a conceptualization store; The index.js code is as follows

import {createStore,combineReducers} from "redux";
import {TagReducer} from "./reducer";

/*
 * 多个reducer汇总的写法(注释区域)
 * 需要用combineReducers方法关联形成一个大的reducer
 * 只有一个就没有必要用combineReducers方法
 */
// const allReducers={
//   tInfo:TagReducer,
//   //...
// }
// const reducers=combineReducers(allReducers);
// const store=createStore(reducers);

/*单个写法*/
const store=createStore(TagReducer);
export default store;

6. Final articles, as long as through a subscribe method, the primary inlet redux project file to associate index.js; index.js root directory file code as follows: (index.js entry file belonging to the project)

/*根目录中index.js文件*/
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux";

const render=()=>{
  ReactDOM.render(<App />, document.getElementById('root'));
};
render();
const unsubscribe=store.subscribe(()=>{
  render();
});

serviceWorker.unregister();

The assembly functions for file App.js, code is as follows: (App.js file belonging inlet assembly)

import React, { Component } from 'react';
import store from "./redux";
import {addTag,delTag} from "./redux/actions";
import './App.css';

class App extends Component {
  addTagFuns=()=>{
    const obj={
      "name":"标签二"
    };
    store.dispatch(addTag(obj));
  }
  delTagFuns=()=>{
    store.dispatch(delTag());
  }
  render() {
    const tag_list=store.getState();
    let tag_com=tag_list.map((item)=>{
      return (<span class="tag">{item.name}</span>);
    })
    return (
      <div className="App">
        <div>
          <button type="button" onClick={this.addTagFuns}>新增标签</button>
          <button type="button" onClick={this.delTagFuns}>删除标签</button>
        </div>
        {tag_com}
      </div>
    );
  }
}

export default App;

subscribe (funs) This function is used to store the subscription changes, each time you store carried dispatch (action) will trigger the function call subscribe registered, this is not the case in practice must be to see their own scenarios, if you after the store wanted to change the view view have to follow the changes, then you need to subscribe to store global change;

Guess you like

Origin blog.csdn.net/u012475786/article/details/88974145