create 一个 Context:
// 这里是默认值
export const AlertContext = React.createContext({
open: false,
dispatch: (value) => {},
});
设计 reducer
export const alertReducer = (
state = {
open: false,
},
action,
) => {
switch (action.type) {
case 'OPEN':
return {
open: true,
};
case 'CLOSE':
return {
open: false,
};
default:
return state;
}
};
在根组件中使用 Context.Provider
,只有被其包裹住的组件才能获得 context 的值更新:
<AlertContext.Provider value={{ open, dispatch }}>
// 弹窗组件
<Snackbar open={open} />
// 其他组件
<App />
</AlertContext.Provider>
在其他组件中,要触发值,从 context 取出 dispatch 即可:
const { dispatch } = React.useContext(AlertContext);
return <button onClick={() => {
dispatch({
type: 'OPEN',
payload: {
open: true,
},
});
}}>click</button>