react-redux

react中的数据仓库store:

原理:

  View页面交互使用 store.dispatch() 分发action,action中进行匹配处理找到对应的reducer(对state的处理方法),reducer中相应的reduce对state进行修改操作,在reducer中处理好的数据返回给对应的aciton,

  action 需要返回一个新的state,在页面View中使用store.getState()

建立文件夹:/src/store

在文件夹中新建文件:

index.js => 全局store对象

reducer.js=> 处理action的方法,state数据,修改state的方法

action.js=>匹配action

第一步:

  页面分发action:

  1.引入store:

   import  store from  '../src/index';

  2.分发action:

   一般是触发某个事件才进行action的分发:

   store.dispatch({ type:action的type , 接收的参数名称:参数值 })

  3.此时可以获取更新后的state:

第二步:

  action中接收进行action的匹配:

  export  function  actionTypeName( 接收的参数 ){

    return  { type:'名称',参数名 }

  }

第三步:

   reducer中具体对state 的修改:

  import  {  XXactionName  }  from  './action.js' ;

  import  { combineReducers  }  from  'redux'

  //  定义reduce的方法,接收两个参数,state和action,可以为state设置默认的值, action 包含携带了的参数

  function  redName  ( state,action ){

    switch(action.type){  //  匹配action
      case XXactionName : 

        return  state + action.num    //  返回新的处理后的state

      default :

        return  state

    }

  }

  function fn2(... , ...){

    ......

  }

  .........     //  可以定义多个reduce处理方法

  //  使用combineReducers将自己定义的reduce方法进行合并

  const  reducer = combineReducers(redName , fn2 , .. . . . )

  export  default  reducer

  

原文地址:https://www.cnblogs.com/VaeVae/p/10256521.html