前言: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);有效減小代碼。