react系列笔记:第一记-redux

时间:2023-01-15 19:00:31

前言:

  目前公司使用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之前的扩展

 

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);有效减少代码。