學(xué)習(xí)背景:
我最近在更新師兄之前用React寫的項(xiàng)目,該項(xiàng)目中各組件的狀態(tài)依賴關(guān)系非常復(fù)雜,為了便于管理組件的狀態(tài),師兄使用了Redux。我最近剛轉(zhuǎn)React,此前沒有用過Redux,借這個(gè)難得的機(jī)會(huì),我學(xué)習(xí)了Redux并對其相關(guān)知識(shí)點(diǎn)進(jìn)行了梳理。
一 Redux解決了什么問題?
學(xué)習(xí)react的朋友都知道組件化是react最擅長的方面,但是在實(shí)際開發(fā)中,隨著應(yīng)用復(fù)雜度地不斷提升,組件之間的狀態(tài)通信變得越來越多,組件之間的耦合也變得越來越重。
這時(shí),Redux誕生了,Redux對所有“組件”說:“你們不要在一對一地寫信通知狀態(tài)了,我是組件群的‘通信云盤’,你們把公共狀態(tài)存在我這,只要某個(gè)狀態(tài)一改變,各組件都能取到狀態(tài)的最新值?!?/p>
二 使用Redux需掌握哪些最精髓的API?
(1)store: store對象是保存公共數(shù)據(jù)的地方,一個(gè)應(yīng)用只能創(chuàng)建一個(gè)store。下面是創(chuàng)建store方式:
import { createStore } from 'redux';
const store = createStore(function);
(2)state:state是store映射的數(shù)據(jù)集合,一個(gè)state 只對應(yīng)一個(gè)view,下面是創(chuàng)建state方法:
import { createStore } from 'redux';
const store = createStore(function);
const state = store.getState(); // 通過store.getState()拿到state
(3)action:state和view捆綁在一起,view發(fā)生變化時(shí)會(huì)用action發(fā)出通知。action是改變state的唯一方法,它本質(zhì)是一個(gè)對象,必須要寫一個(gè)代表action名稱的屬性——type。除此之外,其他屬性可以自由設(shè)置,下面是action對象示例:
const action = {?
? type: 'student_age',?
? age: 12
};
(4)store.dispatch():store.dispatch()是 view 發(fā)出 action 的唯一方法,也可以理解為發(fā)射action通知的唯一方法。下面是使用store.dispatch()的代碼示例:
store.dispatch({
? type: 'student_age',
? age: 12
});
(5)reducer:reducer是一個(gè)計(jì)算state的函數(shù),接受兩個(gè)參數(shù),當(dāng)前的state和action。當(dāng)store收到action通知后,一定要返回一個(gè)全新的state,這樣view才能發(fā)生變化。store接收到action傳來的數(shù)據(jù),然后根據(jù)邏輯計(jì)算數(shù)據(jù),這個(gè)過程就稱為reducer。下面是reduer的代碼示例:
import { createStore } from 'redux';
const reducer = (state = defaultState, action) => {
? switch (action.type) {? ?
? ? case 'student_age':? ? ?
? ? ? return state + action.age;? ?
? ? default: ? ? ?
? ? ? return state;?
}};
const store = createStore(reducer); // 生成store時(shí)傳入reducer
實(shí)際開發(fā)中要在生成store時(shí)傳入reducer,這樣store.dispatch()會(huì)自動(dòng)觸發(fā)reducer函數(shù)執(zhí)行。
(6)store.subscribe():store.subscribe()監(jiān)聽state變化,state一旦變化就自動(dòng)觸發(fā)該函數(shù)。下面是它的代碼示例:
import { createStore } from 'redux';
const store = createStore(reducer);
store.subscribe(listener);
三 Redux的運(yùn)行原理是什么?

四 store有哪些重要方法?
