【发布时间】:2019-12-04 16:34:15
【问题描述】:
我遇到了如何在 ReactJS 应用程序中使用 ContextAPI 的问题。 我想要这样的东西:
<App>
<Alerts/>
<MyComponent />
</App>
我有一个上下文来管理警报,如下所示:
const initialState = [];
const [state, dispatch] = useReducer(alertReducer, initialState);
const setAlert = alert => {
const id = uuidv4();
dispatch({
type: SET_ALERT,
payload: { ...alert, id },
});
};
然后我将在其他上下文中进行一些操作,例如:
const getErrors = async () => {
const res = await axios.get( .... )
dispatch({ type: CLEAR, payload: res });
};
有什么方法可以在 clearErrors 中向警报上下文发送操作?
基本上我希望能够在不同的上下文中更新状态。
我正在尝试拥有一个 toast 管理器...并在某些 axios 函数中某个操作成功或出错时发送“toasts”。
恐怕我会以某种方式使这变得复杂,但我试图在谷歌搜索中找到一些亮点,但我只找到组件之间的共享状态,但没有找到来自不同上下文的更新状态。
使用 redux,因为我们有一个集中式存储,我们可以调度所有 reducer 捕获的操作,但使用 contextapi 不会发生......
任何帮助将不胜感激。
问候
【问题讨论】:
标签: reactjs react-hooks react-context