為什么要使用 React-Redux?

通常我們使用 react 開發(fā)項目的時候,會把 redux 和 react-redux 庫引進來,你是否思考過為什么需要 react-redux 庫呢?今天就一起來分析一下這個問題。
Redux 本身是一個獨立的庫,可以與任何 UI 框架一起使用,包括 React,Angular,Vue,Ember 和 vanilla JS。盡管 Redux 和 React 經(jīng)常一起使用,但它們彼此獨立。
如果將 Redux 與任何類型的 UI 框架一起使用,通常將使用“UI 綁定”庫將 Redux 與 UI 框架綁定在一起,而不是通過 UI 代碼直接與 store 進行交互。
比如這樣:
// 簡單了解一下 redux 實現(xiàn)function createStore(reducer) {var state;var listeners = []function getState() {return state}function subscribe(listener) {listeners.push(listener)return function unsubscribe() {var index = listeners.indexOf(listener)listeners.splice(index, 1)}}function dispatch(action) {state = reducer(state, action)listeners.forEach(listener => listener())}dispatch({})return { dispatch, subscribe, getState }}
// 1) 創(chuàng)建 storeconst store = createStore(counter)// 2) subscription store 訂閱更新,然后重新渲染 UI 界面store.subscribe(render);const valueEl = document.getElementById('value');// 3. subscription callback runs 訂閱回調(diào)執(zhí)行:function render() {// 3.1) 獲取當前 store stateconst state = store.getState();// 3.2) 提取所需數(shù)據(jù)const newValue = state.toString();// 3.3) 通過新的 state 去更新 UI 界面valueEl.innerHTML = newValue;}// 4) 根據(jù) store state 初始化 UI 界面render();// 5) Dispatch actions 派發(fā)document.getElementById("increment").addEventListener('click', () => {store.dispatch({type : "INCREMENT"});})
對任何 UI 層使用 Redux 都需要相同的一致步驟:
1、創(chuàng)建 Redux store
2、訂閱更新
3、在訂閱回調(diào)中:
1、獲取當前 store 狀態(tài)
2、提取此 UI 所需的數(shù)據(jù)
3、用數(shù)據(jù)更新 UI
4、如有必要,使用初始狀態(tài)呈現(xiàn) UI
5、通過 dispatch Redux actions 響應 UI 輸入
盡管可以手動編寫此邏輯,但這樣做會變得非常重復。另外,優(yōu)化 UI 性能將需要復雜的邏輯。
訂閱存儲,檢查更新的數(shù)據(jù)以及觸發(fā)重新渲染的過程可以變得更加通用和可復用。UI 綁定庫(例如 React Redux)處理 store 交互邏輯,因此您不必自己編寫該代碼。
評論
圖片
表情
