useReactive Hook 使用说明
功能概述
useReactive 是一个增强版的 React 状态管理 Hook,提供响应式状态更新、状态引用获取和状态重置功能,特别适合管理复杂对象状态。
基础用法
import { useReactive } from './useReactive';
interface UserState {
name: string;
age: number;
address: string;
}
function UserProfile() {
const [user, updateUser, getUser, resetUser] = useReactive<UserState>({
name: '张三',
age: 25,
address: '北京市',
});
// 更新部分状态
const handleUpdate = () => {
updateUser({ age: 26 });
// 或使用函数式更新
updateUser(prev => ({ ...prev, age: prev.age + 1 }));
};
// 获取当前状态快照
const logState = () => {
console.log(getUser());
};
return (
<div>
<p>姓名: {user.name}</p>
<p>年龄: {user.age}</p>
<button onClick={handleUpdate}>增加年龄</button>
<button onClick={logState}>打印状态</button>
<button onClick={resetUser}>重置</button>
</div>
);
}
API 说明
输入参数
| 参数 | 类型 | 必填 | 说明 | | ------------ | ---- | ------- | ------ | --- | ------------ | | initialState | T | extends | object | 是 | 初始状态对象 |
返回值
返回一个包含四个元素的元组:
| 索引 | 名称 | 类型 | 说明 |
|---|---|---|---|
| 0 | state | T | 当前状态 |
| 1 | updateState | (newState: Partial<T> ((prev: T) => Partial<T>)) => void |
更新函数 |
| 2 | getState | () => T | 获取最新状态函数 |
| 3 | resetState | () => void | 重置状态函数 |
高级用法
在异步操作中使用
const [form, updateForm, getState, onReset] = useReactive(initialForm);
const submit = async () => {
// 获取提交时的最新状态
const currentForm = getState();
await api.submit(currentForm);
};