1. Context API

1.1 核心概念

通过Provider + useContext实现全局状态管理

  • useContext:用来在组件树中共享数据,避免多层 props 传递。

  • useReducer:用来管理复杂的状态逻辑(类似 Redux 的 reducer 思路)。

组合起来,你就能实现一个 小型 Redux,但更轻量,代码量也少。是一个局部可控的状态中心

Context(上下文对象)

作用:存储你希望在组件树中共享的状态或数据。

特点

  • defaultValue 是当组件树上层没有 Provider 时使用的默认值。

  • Context 本身只是一个容器,不管理状态的更新。

Provider(提供者)

作用:将状态传递给子孙组件。

特点

  • value 是共享的数据或状态。

  • Provider 可以嵌套,每个 Provider 都会覆盖上层 Provider 的值。

Consumer(消费者)

作用:在组件中获取 Context 的值。

特点

  • 函数子组件接收当前 Context 的值。

  • 现代 React 更常用 useContext Hook 替代 Consumer。

useContext Hook

作用:在函数组件中直接获取 Context 值。

特点

  • 简化了 Consumer 的写法

  • 当 Provider 的 value 改变时,订阅该 Context 的组件会重新渲染

更新 Context 数据

Context 本身不提供修改方法,通常结合 useStateuseReducer 使用

特点

  • 子组件可以通过 useContext(MyContext) 调用 setUser 更新状态。

1.2 数据流

1、创建 Context。

2、Provider 提供状态

3、子组件订阅 Context

4、子组件更新状态(可选)

5、Provider 更新 value

1.3 使用示例

想要使用useContext,首先要创建context。使用createContext,通过Provider提供数据,然后在子组件中调用useContext消费数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 1. 创建 Context
const ThemeContext = createContext("light");

function App() {
return (
// 2. Provider 提供数据
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}

function Child() {
// 3. useContext 消费数据
const theme = useContext(ThemeContext);
return <p>当前主题:{theme}</p>; // 输出 "dark"
}

1.4 项目使用实例

全局认证信息管理

通过 Context 把认证信息(如 token、用户信息)注入整个组件树,使任意子组件都可以访问或更新

1、创建context

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//1、创建Context
import { FC, ReactNode, useReducer, createContext, useContext, useEffect } from 'react';
const AuthContext = createContext<AuthContextType>({
appStore: initialState,
// eslint-disable-next-line @typescript-eslint/no-empty-function
appDispatch() {},
});
const StoreProviderContext: FC<RenderType> = (props) => {
const { deviceLis = [] } = props;
// 生成redux,appStore 保存状态,appDispatch 更新状态
const [appStore, appDispatch] = useReducer(storeReduce, initialState);

useEffect(() => {
// 更新个人信息列表
if (deviceLis && deviceLis.length) {
appDispatch({ type: 'updateUserDiveceLis', data: { userDiviceLis: deviceLis } });
appDispatch({ type: 'updateUserDiviceInfo', data: { userDiviceInfo: deviceLis[0] } });
}
}, [deviceLis]);
//props.children 表示所有被 StoreProviderContext 包裹的子组件都能访问到这个上下文。
//AuthContext.Provider 是 React Context API 的提供者,必须传一个 value,这个 value 就是要共享给子组件的内容。
return <AuthContext.Provider value={{ appStore, appDispatch }}>{props.children}</AuthContext.Provider>;
};

2、定义reduce

定义不同的动作,根据不同的 动作,返回一个新的 state。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
*
* @desc State Reduce 提交 Active
*/
export const storeReduce = (state: InitialStateType, active: ActiveType): InitialStateType => {
switch (active.type) {
case 'updateUserDiveceLis':
return { ...state, userDiviceLis: active.data?.userDiviceLis || [] };

case 'updateUserDiviceInfo':
return { ...state, userDiviceInfo: active.data?.userDiviceInfo || null };

default:
return state;
}
};

3、在父组件中提供状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const StoreProviderContext: FC<RenderType> = (props) => {
const { deviceLis = [] } = props;
// 生成 Store
const [appStore, appDispatch] = useReducer(storeReduce, initialState);

useEffect(() => {
// 更新个人信息列表
if (deviceLis && deviceLis.length) {
appDispatch({ type: 'updateUserDiveceLis', data: { userDiviceLis: deviceLis } });
appDispatch({ type: 'updateUserDiviceInfo', data: { userDiviceInfo: deviceLis[0] } });
}
}, [deviceLis]);

return <AuthContext.Provider value={{ appStore, appDispatch }}>{props.children}</AuthContext.Provider>;
};

4、在子组件使用

1
2
3
4
5
6
7
8
9
10
11
12
13
import { MessageInstance } from '@/context/Message';
import { AuthProviderContextInstance } from '@/context/AuthProviderContext';
const App: FC = () => {
return (
<>
{/* {挂载 Message 节点} */}
<MessageInstance.Render />
<AuthProviderContextInstance.Render>
<Outlet />
</AuthProviderContextInstance.Render>
</>
);
}

在app.tsx中定义provider,那么其所有的子组件都可以共享组件状态。

特点:

  • 使用 useReducer 管理应用级状态

  • 管理用户设备信息、认证状态等

  • 提供 appStore 和 appDispatch 给子组件

将元数据管理修改为useContext+useRedux组成的全局状态管理

1、首先需要定义State和Action

State是全局状态组件中的所有数据

Action是全局状态组件中的所有操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface State {
productType: string;
moudlelist: MoudleList;
productList: ProductList[];
selectedProduct: ProductList;
selectedMoudle: MoudleList;
protocolId: string;
treelist: any[];
isSelect: boolean;
loading: boolean;
}

interface Action {
type:
| 'SET_MOUDLE_LIST'
| 'SET_PRODUCT_LIST'
| 'SET_SELECTED_PRODUCT'
| 'SET_SELECTED_MOUDLE'
| 'SET_PROTOCOL_ID'
| 'SET_TREE_LIST'
| 'SET_IS_SELECT'
| 'SET_LOADING'
| 'SET_PRODUCT_TYPE';
payload: any;
}

2、接着定义reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const reducer = (state: State, action: Action): State => {
switch (action.type) {
//设置模块列表
case 'SET_MOUDLE_LIST':
return { ...state, moudlelist: action.payload };
//设置产品列表
case 'SET_PRODUCT_LIST':
return { ...state, productList: action.payload };
//设置选中产品
case 'SET_SELECTED_PRODUCT':
return { ...state, selectedProduct: action.payload };
//设置选中模块
case 'SET_SELECTED_MOUDLE':
return { ...state, selectedMoudle: action.payload };
//设置协议ID
case 'SET_PROTOCOL_ID':
return { ...state, protocolId: action.payload };
//设置树形数据
case 'SET_TREE_LIST':
return { ...state, treelist: action.payload };
//设置是否选中
case 'SET_IS_SELECT':
return { ...state, isSelect: action.payload };
//设置加载状态
case 'SET_LOADING':
return { ...state, loading: action.payload };
//设置产品类型
case 'SET_PRODUCT_TYPE':
return { ...state, productType: action.payload };
default:
return state;
}
};

3、初始化state状态

1
2
3
4
5
6
7
8
9
10
11
const initialState: State = {
productType: '',
moudlelist: {} as MoudleList,
productList: [],
selectedProduct: {} as ProductList,
selectedMoudle: {} as MoudleList,
protocolId: '',
treelist: [],
isSelect: false,
loading: false,
};

4、调用createContext创建上下文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const DataContext = createContext<
| {
state: State;
dispatch: React.Dispatch<Action>;
// 业务方法
getProductList: () => Promise<ProductList[]>;
getMoudleList: (productType: number, id: number) => void;
getTreeData: (protocolId: bigint, fieldCondition: string) => Promise<any[]>;
getDataTypeList: () => Promise<string[]>;
addMetaData: (data: MetaData) => Promise<any>;
reset: () => void;
}
| undefined
>(undefined);

5、定义redux仓库

1
2
3
4
5
6
7
8
export const useDataStore = () => {
const context = useContext(DataContext);
if (!context) {
throw new Error('useDataStore must be used within a DataProvider');
}
return context;
};

6、定义provider方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Provider组件
export const DataProvider: React.FC<{ children: ReactNode; initialProductType?: string; selectedProduct?: ProductList }> = ({
children,
initialProductType,
selectedProduct,
}) => {
const [state, dispatch] = useReducer(reducer, {
...initialState,
productType: initialProductType || '',
});

// 初始化时设置productType
useEffect(() => {
if (initialProductType) {
dispatch({ type: 'SET_PRODUCT_TYPE', payload: initialProductType });
}
if (selectedProduct) {
dispatch({ type: 'SET_SELECTED_PRODUCT', payload: selectedProduct });
}
}, [initialProductType, selectedProduct]);

// 获取产品列表
const getProductList = useCallback(async (): Promise<ProductList[]> => {
console.log('getProductList called');
try {
const res = await getDataViewProduct();
if (res.code === '0') {
dispatch({ type: 'SET_PRODUCT_LIST', payload: res.data });
return res.data;
} else {
return [];
}
} catch (error) {
console.error('获取产品列表失败:', error);
return [];
}
}, []);

// 获取模块列表
const getMoudleList = useCallback(async (productType: number, id: number) => {
console.log('getMoudleList called with:', { productType, id });

dispatch({ type: 'SET_LOADING', payload: true });
try {
const res = await getProtocolList({ productType, id });
console.log('getProtocolList response:', res);

if (res.code === '0' && res.data && res.data.content) {
// 成功获取数据
dispatch({ type: 'SET_MOUDLE_LIST', payload: res.data.content });
console.log('模块列表更新成功:', res.data.content);
} else {
// API返回错误或数据格式不正确
console.warn('API返回错误或数据格式不正确:', res);
dispatch({ type: 'SET_MOUDLE_LIST', payload: {} as MoudleList });
}
} catch (error) {
// 网络错误或其他异常
console.error('获取模块列表失败:', error);
dispatch({ type: 'SET_MOUDLE_LIST', payload: {} as MoudleList });
} finally {
dispatch({ type: 'SET_LOADING', payload: false });
}
}, []);

// 获取数据类型
const getDataTypeList = useCallback(async (): Promise<string[]> => {
try {
const res = await getDataType();
if (res.code === '0') {
return res.data;
}
return [];
} catch (error) {
console.error('获取数据类型失败:', error);
return [];
}
}, []);

// 获取树形数据
const getTreeData = useCallback(async (protocolId: bigint, fieldCondition: string): Promise<any[]> => {
dispatch({ type: 'SET_LOADING', payload: true });
try {
const res = await getProtocolDetailList({ protocolId, fieldCondition });
if (res.code === '0') {
dispatch({ type: 'SET_TREE_LIST', payload: res.data });
return res.data;
} else {
return [];
}
} catch (error) {
console.error('获取树形数据失败:', error);
return [];
} finally {
dispatch({ type: 'SET_LOADING', payload: false });
}
}, []);

// 添加元数据
const addMetaDataHandler = useCallback(async (data: MetaData): Promise<any> => {
try {
const res = await addMetaData(data);
return res;
} catch (error) {
console.error('添加元数据失败:', error);
throw error;
}
}, []);

// 重置状态
const reset = useCallback(() => {
dispatch({ type: 'SET_LOADING', payload: false });
dispatch({ type: 'SET_MOUDLE_LIST', payload: [] });
dispatch({ type: 'SET_PRODUCT_LIST', payload: [] });
dispatch({ type: 'SET_SELECTED_PRODUCT', payload: {} });
dispatch({ type: 'SET_SELECTED_MOUDLE', payload: {} });
dispatch({ type: 'SET_PROTOCOL_ID', payload: '' });
dispatch({ type: 'SET_TREE_LIST', payload: [] });
dispatch({ type: 'SET_IS_SELECT', payload: false });
}, []);

const contextValue = {
state,
dispatch,
getProductList,
getMoudleList,
getTreeData,
getDataTypeList,
addMetaData: addMetaDataHandler,
reset,
};

return <DataContext.Provider value={contextValue}>{children}</DataContext.Provider>;
};

7、在入口函数中使用DataProvider组件包裹组件

1
2
3
4
5
6
7
8
9
10
11
export default function DataNesting(props: { productType: string; selectedProduct: ProductList }) {
const { productType, selectedProduct } = props;

return (
<DataProvider initialProductType={productType} selectedProduct={selectedProduct}>
<div className={styles['datanesting-container']}>
<ParamView />
</div>
</DataProvider>
);
}

8、在需要的地方调用仓库

1
const { state, dispatch, getTreeData, getMoudleList } = useDataStore();

2. Redux

Redux 是一个 JavaScript 状态管理库,最常用于 React 应用,但也可以搭配 Vue、Angular 或者原生 JS 使用。它的核心思想是:

👉 单一数据源、状态只读、用纯函数来更新状态

2.1 核心概念

Store(存储)

Action(动作)

Reducer(状态更新函数)

Dispatch(派发)

Subscribe(订阅)

2.2 数据流

Redux 强调 单向数据流

  1. 用户操作触发 dispatch(action)

  2. Reducer 根据 action 生成新的 state

  3. Store 保存新的 state

  4. 视图(UI)重新渲染

⚠️注意

2.3 使用实例

1、安装包依赖

1
pnpm add @reduxjs/toolkit react-redux

2、创建目录

src/reduxstore/

├── index.ts # 主 store 配置

├── hooks.ts # 类型化的 Redux hooks

├── dataNestHooks.ts # 业务相关的 hooks

└── slices/

└── dataNestSlice.ts # 具体的 slice 实现

3、创建Redux Store配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { configureStore } from '@reduxjs/toolkit';
import dataNestReducer from './slices/dataNestSlice';

export const store = configureStore({
reducer: {
dataNest: dataNestReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: ['dataNest/getTreeData/fulfilled', 'dataNest/getMenuList/fulfilled'],
ignoredPaths: ['dataNest.treelist'],
},
}),
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

4、创建类型化的钩子

1
2
3
4
5
import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux';
import type { RootState, AppDispatch } from './index';

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

说明:

  • 创建类型化的 useDispatch 和 useSelector hooks

  • 确保类型安全,避免在组件中使用时出现类型错误

5、创建Redux Slice

首先定义状态类型和初始状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export interface DataNestState {
productlist: ProductList;
selectedProduct?: ProductList;
productType?: number | null;
moudlelist: MoudleList;
protocolId: string;
selectedMoudle?: MoudleList;
treelist: [];
isSelect: boolean;
loading: boolean;
}

const initialState: DataNestState = {
productlist: {},
selectedProduct: {},
productType: 0,
moudlelist: {},
protocolId: '',
treelist: [],
selectedMoudle: {},
isSelect: false,
loading: false,
};

接着创建异步的thunk函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export const getProductList = createAsyncThunk('dataNest/getProductList', async () => {
const res = await getDataViewProduct();
if (res.code === '0') {
return res.data;
} else {
return [];
}
});

export const getMoudleList = createAsyncThunk('dataNest/getMoudleList', async ({ productType, id }: { productType: number; id: number }) => {
const res = await getProtocolList({ productType, id });
if (res.code === '0') {
return res.data.content;
} else {
return {};
}
});

说明:

  • createAsyncThunk:创建异步 action

  • 自动处理 pending、fulfilled、rejected 状态

  • 返回 Promise,便于在组件中使用

创建slice

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const dataNestSlice = createSlice({
name: 'dataNest',
initialState,
reducers: {
// 同步 actions
dispatch: (state, action: PayloadAction<Partial<DataNestState>>) => {
Object.assign(state, action.payload);
},
reset: () => initialState,
setSelectedProduct: (state, action: PayloadAction<ProductList>) => {
state.selectedProduct = action.payload;
},
// ... 其他同步 actions
},
extraReducers: (builder) => {
builder
// 处理异步 thunk 的状态
.addCase(getProductList.pending, (state) => {
state.loading = true;
})
.addCase(getProductList.fulfilled, (state, action) => {
state.productlist = action.payload;
state.loading = false;
})
.addCase(getProductList.rejected, (state) => {
state.loading = false;
})
// ... 其他异步状态处理
},
});

关键点:

  • reducers:定义同步 actions

  • extraReducers:处理异步 thunk 的状态变化

  • 使用 Immer,可以直接修改 state

6、创建业务hook

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export const useDataNestStore = () => {
const dataNestState = useAppSelector((state) => state.dataNest);
return dataNestState;
};

export const useDeviceDispatch = () => {
const reduxDispatch = useAppDispatch();
const dataNestState = useAppSelector((state) => state.dataNest);

// 包装异步函数以保持兼容性
const getProductListWrapper = async () => {
const result = await reduxDispatch(getProductList());
return result.payload;
};

return {
dispatch: dispatchWrapper,
reset: () => reduxDispatch(reset()),
getProductList: getProductListWrapper,
// ... 其他方法
};
};

说明:

  • 封装 Redux 的复杂性

  • 提供与原有 API 兼容的接口

  • 便于组件使用

7、配置provider

1
2
3
4
5
6
7
8
9
10
import { Provider } from 'react-redux';
import { store } from './reduxstore';

root.render(
<Provider store={store}>
<AntdConfigProvider>
<Routers />
</AntdConfigProvider>
</Provider>,
);

8、调用store

1
2
const { selectedProduct, loading } = useDataNestStore();
const { getProductList, dispatch } = useDeviceDispatch();

3. Zustand

3.1 核心概念

Zustand 是一个 轻量级 React 状态管理库,由 JotaiReact-spring 的作者开发。可以有多个store,为不同的业务定义不同的store仓库。

State(状态)

  • 概念:store 中保存的数据就是 state,可以是对象、数组、基本类型等。

  • 特点

    • 状态是响应式的,订阅它的组件会在状态改变时重新渲染。

    • 状态更新不需要 reducer 或 action,直接调用更新函数即可。

Actions / 更新函数

  • 概念:store 中定义的函数,用来修改状态。

  • 特点

    • 可以直接修改状态(用 setget)。

    • 可以写成复杂逻辑,包括异步请求。

Selectors / 选择性订阅

  • 概念:组件可以订阅 store 中的部分状态,而不是整个 store。

  • 作用:优化性能,避免状态更新导致不相关组件重新渲染。

中间件(Middleware,可选)

  • 概念:增强 store 功能,比如持久化、日志记录、调试等。

3.2 数据流

  1. 创建 Store

    • create() 定义状态和更新函数(actions)。
  2. 组件订阅状态(Selector)

    • 组件通过 useStore(state => state.someValue) 订阅 store 的部分状态。
  3. 组件调用 Actions 更新状态

    • 调用 store 内定义的函数(例如 increment()setUser())来修改状态。
  4. Store 更新状态

    • 通过定义的dispatch 函数更新 store 的状态,同时触发所有订阅了该状态的组件重新渲染。
  5. 组件接收最新状态重新渲染

3.3 使用实例

1、定义数据类型及执行的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
export type DataNestState = {
productlist: ProductList; //设备列表中设备的信息
selectedProduct?: ProductList; // 被选中的设备信息
productType?: number | null; //被选中的设备id
moudlelist: MoudleList; // 模块列表
protocolId: string; // 被选中协议id
selectedMoudle?: MoudleList; // 被选中的模块(协议)信息
treelist: []; // 树形数据
isSelect: boolean; // 左侧模块是否选中,用于控制新增元数据按钮是否显示
loading: boolean; // 是否加载中
};
// 数据状态变更
type DispatchType = {
// state: DataNestState; // 状态
dispatch: (value: Partial<DataNestState>) => void; // 状态变更
reset: () => void; // 重置状态
getProductList: () => Promise<ProductList>; // 获取产品列表
getMoudleList: (productType: number, id: number) => void; // 获取表格数据
getTreeData: (protocolId: bigint, searchparam: string) => Promise<[]>; // 获取树形数据
getMenuList: (protocolId: string) => Promise<[]>; // 获取树形数据
getDataTypeList: () => Promise<string[]>; // 获取数据类型列表
};
// 数据初始状态
const dataConfig: DataNestState = {
productlist: {},
selectedProduct: {},
productType: 0,
moudlelist: {},
protocolId: '',
treelist: [],
selectedMoudle: {},
isSelect: false,
loading: false,
}

2、创建store仓库

使用create函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
*
* 仓库管理
*/
export const useDataNestStore = create<DataNestState & DispatchType>((set, get) => ({
...dataConfig,
// state: () => get(),
dispatch: (value) => set(() => ({ ...value })),
reset: () => {
set(() => dataConfig);
},
// 获取产品列表
getProductList: async () => {
const res = await getDataViewProduct().then((res) => {
if (res.code === '0') {
return res.data;
} else {
return [];
}
});
return res;
},
// 获取模块列表
getMoudleList: (productType: number, id: number) => {
set(() => ({ loading: true }));
getProtocolList({ productType, id }).then((res) => {
if (res.code === '0') {
set(() => ({ moudlelist: res.data.content }));
set(() => ({ loading: false }));
} else {
set(() => ({ loading: false }));
set(() => ({ moudlelist: {} }));
}
});
},
// 获取数据类型
getDataTypeList: async () => {
const res = await getDataType();
if (res.code === '0') {
return res.data;
}
return [];
},
getTreeData: async (protocolId: bigint, fieldCondition: string) => {
set(() => ({ loading: true }));
const res = await getProtocolDetailList({ protocolId: protocolId, fieldCondition: fieldCondition }).then((res) => {
if (res.code === '0') {
set(() => ({ treelist: res.data }));
set(() => ({ loading: false }));
return res.data;
} else {
set(() => ({ loading: false }));
return [];
}
});
set(() => ({ loading: false }));
return res;
},
getMenuList: async (protocolId: string) => {
const res = await getProtocolDetailList({ protocolId: BigInt(protocolId), fieldCondition: '' }).then((res) => {
if (res.code === '0') {
return res.data;
} else {
return [];
}
});
return res;
},
addMetaData: async (data: MetaData) => {
const res = await addMetaData(data);
return res;
},
}));

3、定义dispatch触发状态变更。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
*
* 触发状态变更
*/
export const useDeviceDispatch = () => {
const dispatch = useDataNestStore((state) => state.dispatch);
const reset = useDataNestStore((state) => state.reset);
const getProductList = useDataNestStore((state) => state.getProductList);
const getTableList = useDataNestStore((state) => state.getMoudleList);
const getTreeData = useDataNestStore((state) => state.getTreeData);
const getDataTypeList = useDataNestStore((state) => state.getDataTypeList);
return { dispatch, reset, getProductList, getTableList, getTreeData, getDataTypeList };
};

4、调用store中的方法及参数

1
const { selectedProduct, getMoudleList, loading, dispatch } = useDataNestStore();

5、调用dispatch函数更新状态,调用store中的方法更新状态

1
2
dispatch({ loading: true });
getMoudleList(Number(selectedProduct?.productType), 0);

4. 全局状态管理器对比

4.1 useContext + useReducer

  • 定位:React 内置的“轻量级状态管理”,适合小规模应用或局部状态共享。

  • 特点

    • useReducer 负责处理 state 和 action(类似 Redux reducer)。

    • useContext 负责跨组件传递 state 和 dispatch。

    • 状态保存在 React 组件树中,每次更新都会触发 相关 Provider 下所有子组件的重新渲染(除非配合 memo/useMemo 优化)。

  • 适用场景:小项目,局部共享状态(如主题、登录信息),对全局性能要求不高时。

4.2 Zustand

  • 定位:现代化、极简的 React 状态管理库。

  • 特点

    • 没有样板代码,直接定义一个“store 函数”,很像写普通 JS 对象。

    • 不依赖 React Context,所以避免了“Provider 大爆炸”和无关组件渲染。

    • 支持选择性订阅(useStore(state => state.xxx)),只有依赖的数据变了,组件才会更新。

    • 内置中间件支持(持久化、日志、immer 等),使用体验很灵活。

  • 适用场景:中小型到中大型项目,需要比 Redux 更少模板代码,同时关注性能和易用性。

4.3 Redux

  • 定位:老牌状态管理框架,适合大型应用。

  • 特点

    • 单一数据源(一个 Store),数据流严格单向。

    • 强约束:必须通过 Action → Reducer → 新 State 的流程,方便调试和回溯。

    • 生态庞大:Redux Toolkit 简化了很多样板代码,DevTools 支持强大。

    • 但是:代码量偏多,学习曲线高于 Zustand/useReducer。

  • 适用场景:大型复杂项目,需要严格的状态管理规范、调试工具和团队协作时。