Redux 是一個 集中式 狀態管理框架,所有狀態存儲在一個 全局 Store 中,并通過 Action 觸發 Reducer 進行數據更新。。
1.安裝
npm install redux miniprogram-computed
2.創建
// store.js
import { createStore } from "redux";// 定義初始狀態
const initialState = {userInfo: null
};// 定義 Reducer
function reducer(state = initialState, action) {switch (action.type) {case "SET_USER":return { ...state, userInfo: action.payload };default:return state;}
}// 創建 Store
export const store = createStore(reducer);
3.使用
// page.js
import { store } from "../../store";// 獲取全局狀態
console.log(store.getState().userInfo);// 更新全局狀態
store.dispatch({ type: "SET_USER", payload: { name: "張三" } });