目录复制
react中实现全局状态共享
1. redux概括
主要用处
- provider内的组件状态全局共享
- 跨组件传值,改变值
主要组成
- store 储存数据源
- reducer 负责将通过不同行为改变状态
- action 行为 一般由行为类型+新状态
- dispatch 派遣(调用)reducer的方法
1.1 redux、react-redux使用
git项目 链接: 类组件与函数组件中redux的基本使用.
2. Hook实现全局状态共享(Hook+ts)
- 创建一个全局上下文(相当于store)
interface IglobalContext {
value: any;
dispatch?: (action: { type: actionType; value?: number }) => void;
}
const globalContext = createContext<IglobalContext>({ value: 0 });
- 创建 reducer (并自定义Hook返回)
const useGlobal = () => {
const reducers = (
state: any,
action: { type: actionType; value?: number },
) => {
switch (action.type) {
case actionTypeEnum.ADD:
return {
...state,
number: state.number + action.value,
};
case actionTypeEnum.SUB:
return {
...state,
number: state.number - (action.value ?? 0),
};
case actionTypeEnum.INV:
return {
...state,
number: Math.pow(state.number, 2),
};
case actionTypeEnum.EMPTY:
return {
...state,
number: 0,
};
default:
return state;
}
};
const [state, dispatch] = useReducer(reducers, { number: 0 });
const { number } = state;
return { number, dispatch };
};
- Provider全局 包裹使用上下文
// 调用自定义Hook
const { number, dispatch } = useGlobal();
<globalContext.Provider value={{ value: number, dispatch }}>
<Foo />
<Foo2 />
</globalContext.Provider>
- 其中 actionType
type actionType = 'add' | 'sub' | 'inv' | 'empty'; //加|减|乘方|清空
enum actionTypeEnum {
ADD = 'add',
SUB = 'sub',
INV = 'inv',
EMPTY = 'empty',
}
- 组件1中使用
interface IFooProps {}
const Foo: FC<IFooProps> = () => {
const { value, dispatch } = useContext(globalContext);
return (
<div>
<h1> 组件1 共享全局值 : {value}</h1>
<div>
<Radio.Group>
<Radio.Button
value="add"
onClick={() => {
dispatch?.({ type: 'add', value: 1 });
}}
>
加
</Radio.Button>
<Radio.Button
value="sub"
onClick={() => {
dispatch?.({ type: 'sub', value: 1 });
}}
>
减
</Radio.Button>
<Radio.Button
value="inv"
onClick={() => {
dispatch?.({ type: 'inv', value: 1 });
}}
>
乘方
</Radio.Button>
<Radio.Button
value="empty"
onClick={() => {
dispatch?.({ type: 'empty' });
}}
>
清零
</Radio.Button>
</Radio.Group>
</div>
</div>
);
};
- 组件2 使用
const Foo2: FC<IFooProps> = () => {
const { value } = useContext(globalContext);
return <h1 style={{ marginTop: '20px' }}>组件2 共享全局值: {value}</h1>;
};