- 使用对象管理多个状态
可以使用一个 useState 钩子管理一个对象,所有相关的变量都放在该对象中。
import React, { useState, useEffect } from 'react';
const Home = () => {
const [state, setState] = useState({
getCode: '',
version: '高级版',
validity: '2025-03-04',
balance: 2333,
status: { ongoing: 0, success: 0, failed: 0 },
});
useEffect(() => {
setState((prevState) => ({ ...prevState, getCode: 1111}));
}, []);
return (
<div>
<div>{state.getCode}</div>
<div>{state.version}</div>
<div>{state.validity}</div>
<div>{state.balance}</div>
</div>
);};export default Home;
优点
使用一个状态对象将多个变量组织在一起。
更新状态时,使用展开运算符 … 保留未修改的字段。
- 使用 useReducer
当状态较为复杂且需要更新逻辑时,使用 useReducer 是一种更优雅的选择
import React, { useReducer, useEffect } from 'react';
// 定义初始状态
const initialState = {
getCode: '',
version: '高级版',
validity: '2025-03-04',
balance: 2333,
status: { ongoing: 0, success: 0, failed: 0 },
};
// 定义 reducer 函数
function reducer(state, action) {
switch (action.type) {
case 'SET_CODE':
return { ...state, getCode: action.payload };
case 'SET_BALANCE':
return { ...state, balance: action.payload };
case 'SET_STATUS':
return { ...state, status: { ...state.status, ...action.payload } };
default:
return state;
}
}
const Home = () => {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
dispatch({ type: 'SET_CODE', payload: 111}); // 更新状态
}, []);
return (
<div>
<div>{state.getCode}</div>
<div>{state.version}</div>
<div>{state.validity}</div>
<div>{state.balance}</div>
</div>
);
};
export default Home;
优点
适合复杂的状态管理。
状态更新逻辑集中在 reducer 中,便于维护和扩展。
- 使用自定义 Hook
如果某些状态逻辑是重复的,可以封装成自定义 Hook。
import React, { useEffect, useState } from ‘react’;
// 自定义 Hook
function useQueryParameter(key) {
const [value, setValue] = useState('');
useEffect(() => {
const queryParams = new URLSearchParams(window.location.search);
setValue(queryParams.get(key) || '');
}, [key]);
return value;
}
const Home = () => {
const getCode = useQueryParameter('code'); // 自动解析 URL 参数
return (
<div>
<div>{getCode}</div>
</div>
);
};
export default Home;
优点
可复用的状态逻辑,避免重复代码。
自定义 Hook 简化了某些常用场景的实现。
总结
少量状态:可以直接用多个 useState。
多状态、相关状态:用单个状态对象或 useReducer。
重复逻辑:封装自定义 Hook。