react系列笔记:第一记-redux

前言:react

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

 

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

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

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

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

  API:异步

  一、createStore(reducer,initState,enhancer)async

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

      initState:初始化的state学习

        enhancer:ui

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

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

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

  二、store

      store.getState();

      store.dispatch(action);

      store.subscribe(listen);

      store.replaceReducer(nextReducer)

  三、combinReducers(reducer1,reducer2)

  四、applyMiddleware(...middlewareArr):

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

  五、buildActionCreator

  六、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以前的扩展

 

redux-thunk:中间件,能够接受action为一个函数,而后再函数中作异步操做

 

action creater:

  在看http://www.redux.org.cn/docs/react-redux/以前,我也基本认为action creater基本是脱裤子放屁的事,

      由于在我看来   dispatch({type:xxx,payload:xxx})是更直观的简单的,而dispatch(someFun(xxx)),作的事是一毛同样的就显得多余

可是

      缘由是没赶上真正须要用它的场景啊,仍是那句话,若是你以为这种方式对你没什么用处,那就说明你不须要它,

若是如今有个需求,在dispatch一个addTodo的action的时候,须要作不少验证,或者须要在addTodo以后去dispatch另外一个查询的action,那么这时候就能够经过func的形式,将这部分相关代码写在一块儿,这样就不须要在每一个dispatch的地方只须要dispatch这个actionCreator就好了。

衍生:action creator 生成器

  若是全部的action creator都是 func ()=>{type:xxx,payload:xxx}这样就会有不少这样的代码,简单而厌烦

  action creator生成器 接受(type,args)返回一个action,如:(type,args) => {return {type:xxx,payload:args}} ,而后其余的action creator就能够  const addTodo = fun(xxx,xxx);有效减小代码。

相关文章
相关标签/搜索