小程序中状态管理Redux
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: "张三" } });