Diving into React Redux
2022-02-28
本文介紹 React Redux 的觀念。
關於 React Context 的潛在缺點
React Context 適合用於規模較小、邏輯簡單的 App。
如果開發的 App 比較龐大時,Context 可能會變得很複雜,一個 Provider 所管理的 State 非常多,不同的業務邏輯通通寫在一起很容易搞混。 但如果把不同邏輯各自拆開,卻又會出現以下情況,變成這樣一個巢狀的結構。
除此之外,React Team 成員在 2018 年的 GitHub Comment 中說到 React Context 不適合用在頻繁更換狀態的情境下,比較適合應用在像是 Authentication 等狀態變更頻率較低的地方。
return (
<AuthContextProvider>
<ThemeContextProvider>
<UIInteractionContextProvider>
<UserRegistration />
</UIInteractionContextProvider>
</ThemeContextProvider>
</AuthContextProvider>
);
How Redux works
- The 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 Redux store:
redux.createStore(ReducerFunction)
store.subscribe(Subscriber )
=> Vuex Gettersstore.getState()
store.dispatch
=> Vuex Actions
import { createStore } from 'redux';
// Set Initial State
const initialState = {
counter: 0,
};
// Mutations
const counterReducer = (state = initialState, action) => {
if (action.type === 'INCREMENT') {
return { counter: state.counter + 1 };
}
if (action.type === 'DECREMENT') {
return { counter: state.counter - 1 };
}
return state;
};
// Create Redux store
const store = createStore(counterReducer);
// Getters
const counterSubscriber = () => {
const latestState = store.getState();
console.log(latestState);
};
store.subscribe(counterSubscriber);
// Actions
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
export default store;
Provide Redux store from the highest level (index.js), and set the store
prop as the value {store}
from ./store/index.js
.
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import store from './store/index';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
回顧
看完這篇文章,我們到底有什麼收穫呢?藉由本文可以理解到…
- React Redux