-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Closed
Description
useGlobalState
React Hook 实现一个全局状态的功能,不同页面不同组件使用同一个状态。Preview →
QQ20220824-192401-HD.mp4
Usage
1.先为全局状态设置一个唯一key,或者还可以设置一个初始值
const initStep = 1;
const key = 'global-step';
const [step, setStep] = useGlobalState(key, initStep);或者二次封装一个useGlobalStep
const useGlobalStep = (initStep: number = 0) => {
const key = 'global-step';
useGlobalState(key, initStep);
}2.在其他组件或者页面引入useGlobalState并使用相同的key
const PageA = () => {
const key = 'global-step';
const [step, setStep] = useGlobalState(key, 1);
return <div>
{step}
<Button onClick={() => setStep(step + 1)}>step + 1</Button>
</div>
}
const PageB = () => {
const key = 'global-step';
const [step, setStep] = useGlobalState(key, 1);
return <div>
{step}
<Button onClick={() => setStep(step - 1)}>step - 1</Button>
</div>
}或者使用二次封装的useGlobalStep
const PageA = () => {
const [step, setStep] = useGlobalStep();
return <div>
{step}
<Button onClick={() => setStep(step + 1)}>step + 1</Button>
</div>
}
const PageB = () => {
const [step, setStep] = useGlobalStep();
return <div>
{step}
<Button onClick={() => setStep(step - 1)}>step - 1</Button>
</div>
}API
useGlobalState<T>(key: string, initState?: T): [T, (state: T) => void]
| 参数 | 类型 | 必须? | 描述 |
|---|---|---|---|
| key | string |
Yes | 全局状态的唯一key |
| initState | any |
No | 状态的初始值 |
Demo
Metadata
Metadata
Assignees
Labels
No labels