redux概念

redux就是一个数据集中管理器,且某个数据可以在其他任意地方可以拿到。

主要概念:

(一)state

   容器里的数据

(二)store

  保存数据的容器,用来把action和reducer关联,通过createStore()创建store。

(三)action

  运送数据到store。必写字段type表示action的名字,data表示要运送过去的数据。

const action = {
  type: 'ADD_TODO',
  value: '1'
};

(四)reducer

   响应action发送过来的数据,返回新的state给store从而改变view。

   Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。

const initialState = 0;
const reducer = function (state =initialState, action) {
  switch(action.type){
   case "ADD_TODO":return state + action.data;
   default:return state;   
 } 
};

(五)subscribe() 监听store变化

  一旦监听到state改变,就会自动执行subscribe()

import { createStore } from 'redux';
const store = createStore(reducer);
store.subscribe(()=>{
  //数据变化了
});

(六)dispatch()

   触发action去执行reducer。

store.dispatch()

  

(七)工作流程(来自ruanyifeng.com

(1)首先,用户发出 Action。
store.dispatch(action);

   (2)然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。

let nextState = todoApp(previousState, action);

   (3)State 一旦有变化,Store 就会调用监听函数。

  

// 设置监听函数
store.subscribe(listener);

    (4)listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。


function listerner() {
  let newState = store.getState();
  component.setState(newState);   
}
(八)实例
import  React from  "react";
import ReactDom from "react-dom";
import {createStore} from "redux";

function reducer(state=0,action) {
    switch (action.type) {
        case "ADD":return state +action.data
    }
}

var store = createStore(reducer);

function render(){
    console.log(store.getState())
    ReactDom.render(
        <botton onClick={()=>{store.dispatch({type:"ADD",data:2})}}>
          clickMe!{store.getState()}
        </botton>,document.getElementById("root")
    )
}
render();
store.subscribe(render);



   

原文地址:https://www.cnblogs.com/yangqing22/p/14325851.html