首页 > 其他 > 详细

react系列笔记:第一记-redux

时间:2018-06-01 23:43:53      阅读:295      评论:0      收藏:0      [点我收藏+]

前言:

  目前公司使用dva,对于前不久还是使用原生js的我来说,花了差不多一两周时间,基本掌握如何使用。虽然对于react有一点点基础,但很多地方未深入,很多概念也很模糊,故从本文开始,记录一下系统的学习react的历程。

 

redux:(http://www.redux.org.cn/)

  简单来看,redux基本使用就是这样,create一个store出来,然后通过dispatch action,通过reducer来改变这个store。  

const reducer = combinReducers(reducer1,reducer2)
const sotre = createStore(reducer)//创建store

store.getState();
store.dispatch(action)

  API:

  1、createStore(reducer,initState,enhancer)

      reducer:根reducer,reducer函数接受(state,action),返回新state

      initState:初始化的state

        enhancer:

          官方说明:是一个组合 store creator 的高阶函数,返回一个新的强化过的 store creator。这与 middleware 相似,它也允许你通过复合函数改变 store 接口

          参考:https://segmentfault.com/a/1190000012653724

          自己理解:强化的store creator,返回一个函数,这个函数接收(reducer,inistate,enhancer)然后再在函数内部实现对store创建过程的一个扩展。

  2、store

      store.getState();

      store.dispatch(action);

      store.subscribe(listen);

      store.replaceReducer(nextReducer)

  3、combinReducers(reducer1,reducer2)

  4、applyMiddleware(...middlewareArr):

    中间件,用于扩展redux的dispatch,每一个middleware都接收middleware(dispatch,getState),返回一个fun,函数签名:({ getState, dispatch }) => next => action

  5、buildActionCreator

  6、compose

 

 

redux的三大原则:唯一数据源、store为只读、纯函数修改store(reducer)

 

异步:redux-thunk

applyMiddleware(thunk),把action变成接受dispatch和getState参数的函数,在函数内部进行异步操作,然后直接dispatch(asyncAction);

function asyncAction(){
    return (dispatch,getState)=>{
          if(getState().someCoditions){
              return Promise.resolve();
          }
          dispatch(
      makeASandwichWithSecretSauce(‘My Grandma‘)
    ).then(() =>
      Promise.all([
        dispatch(makeASandwichWithSecretSauce(‘Me‘)),
        dispatch(makeASandwichWithSecretSauce(‘My wife‘))
      ])
    ).then(() =>
      dispatch(makeASandwichWithSecretSauce(‘Our kids‘))
    ).then(() =>
      dispatch(getState().myMoney > 42 ?
        withdrawMoney(42) :
        apologize(‘Me‘, ‘The Sandwich Shop‘)
      )
    );
    }  
}

 

中间件:redux的中间件是在action发起的开始,到达reducer之前的扩展

 

react系列笔记:第一记-redux

原文:https://www.cnblogs.com/laojun/p/9123979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!