React Redux 基本配置與概念介紹
本文介紹 React Redux 的概念與基本設定方式,並且探討何時適合使用 Redux 更勝於 React Context API。
關於 React Context API 的潛在缺點
React Context 適合用於規模較小、邏輯簡單的 App。
如果開發的 App 比較龐大時,Context 可能會變得很複雜,一個 Provider 所管理的 State 非常多,不同的業務邏輯通通寫在一起很容易搞混。 但如果把不同邏輯各自拆開,卻又會出現以下情況,變成這樣一個巢狀的結構。
除此之外,React Team 成員在 2018 年的 GitHub Comment 中說到 React Context 不適合用在頻繁更換狀態的情境下,比較適合應用在像是 Authentication 等狀態變更頻率較低的地方。
1return ( 2 <AuthContextProvider> 3 <ThemeContextProvider> 4 <UIInteractionContextProvider> 5 <UserRegistration /> 6 </UIInteractionContextProvider> 7 </ThemeContextProvider> 8 </AuthContextProvider> 9); 10
Redux 如何運作
-
Redux "Reducer" Function = Vuex Mutations
- Should be a Pure Function: 從 Redux 輸入什麼,就產出對應的東西,不會有其他結果
- Should be NO Side Effect: Cannot send a HTTP Request, write to localStorage, or get data from localStorage
- Input params: Old (Existing) State + Dispatched Action
- Output: New State Object
-
Create a Redux Store:
redux.createStore(ReducerFunction)
-
Redux Subscribe (
store.subscribe(Subscriber)
) = Vuex Gettersstore.getState()
-
Redux Dispatch (
store.dispatch({ type: 'ACTION_TYPE' })
) = Vuex Actions
1import { createStore } from 'redux'; 2 3// Set Initial State 4const initialState = { 5 counter: 0, 6}; 7 8// (Mutations) 9const counterReducer = (state = initialState, action) => { 10 if (action.type === 'INCREMENT') { 11 return { counter: state.counter + 1 }; 12 } 13 if (action.type === 'DECREMENT') { 14 return { counter: state.counter - 1 }; 15 } 16 return state; 17}; 18 19// Create Redux store 20const store = createStore(counterReducer); 21 22// (Getters) 23const counterSubscriber = () => { 24 const latestState = store.getState(); 25 console.log(latestState); 26}; 27store.subscribe(counterSubscriber); 28 29// (Actions) 30store.dispatch({ type: 'INCREMENT' }); 31store.dispatch({ type: 'DECREMENT' }); 32 33export default store; 34
對外提供 Redux Store
Provide Redux store from the highest level (index.js), and set the store
prop as the value {store}
from ./store/index.js
.
1import React from 'react'; 2import ReactDOM from 'react-dom'; 3import { Provider } from 'react-redux'; 4 5import './index.css'; 6import App from './App'; 7import store from './store/index'; 8 9ReactDOM.render( 10 <Provider store={store}> 11 <App /> 12 </Provider>, 13 document.getElementById('root'), 14); 15
回顧
看完這篇文章,我們到底有什麼收穫呢?藉由本文可以理解到…
- React Redux