本文介紹 React Redux 的概念與基本設定方式,並且探討何時適合使用 Redux 更勝於 React Context API。
關於 React Context API 的潛在缺點
React Context 適合用於規模較小、邏輯簡單的 App。
如果開發的 App 比較龐大時,Context 可能會變得很複雜,一個 Provider 所管理的 State 非常多,不同的業務邏輯通通寫在一起很容易搞混。 但如果把不同邏輯各自拆開,卻又會出現以下情況,變成這樣一個巢狀的結構。
除此之外,React Team 成員在 2018 年的 GitHub Comment 中說到 React Context 不適合用在頻繁更換狀態的情境下,比較適合應用在像是 Authentication 等狀態變更頻率較低的地方。
return (
<AuthContextProvider>
<ThemeContextProvider>
<UIInteractionContextProvider>
<UserRegistration />
</UIInteractionContextProvider>
</ThemeContextProvider>
</AuthContextProvider>
);
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
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;
對外提供 Redux 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