从reactjs中的另一个上下文更新上下文
我面临着如何在ReactJS应用程序中使用ContextAPI的问题。 我想要这样的东西:从reactjs中的另一个上下文更新上下文,reactjs,react-hooks,react-context,Reactjs,React Hooks,React Context,我面临着如何在ReactJS应用程序中使用ContextAPI的问题。 我想要这样的东西: <App> <Alerts/> <MyComponent /> </App> const initialState = []; const [state, dispatch] = useReducer(alertReducer, initialState); const setAlert = alert => { cons
<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 manager…并在某些axios函数中出现成功或错误的操作时发送“toast”
我担心我可能会使这件事复杂化,但我试图在谷歌搜索中找到一些线索,但我只找到组件之间的共享状态,而没有来自不同上下文的更新状态
使用redux,因为我们有一个集中的存储,所以我们可以调度一个所有还原程序都能捕获的操作,但是使用contextapi,这不会发生
任何帮助都将不胜感激
关于你在应用程序中有多少上下文并不重要,只要你在层次结构中有更高层次的提供者,你就可以始终以正确的上下文为目标 例如,如果
AlertContextProvider
包装了调用getErrors的组件,那么您肯定可以将警报作为目标
假设MyComponent
调用getErrors
和Alerts
组件是提供者,您的结构将是
<App>
<Alerts>
<MyComponent />
</Alerts>
</App>
问题是getErrors在另一个上下文中,让我们称之为“MyComponentContext”,我想要的是一种清晰的方式,使此上下文与alertContext“接触”…因为操作是异步的,我不想在组件中进行等待…(这将访问两个上下文)您可以使用alertContext包装您的应用程序,因此,您可以在任何地方使用它,因为除非层次结构中有提供程序,否则您无法访问该上下文值。我们的解决方案是将useReducer包装为useReducerWithExtras,然后在此中使用警报上下文。
const [data, dispatch] = useContext(AlertContext);
const getErrors = async () => {
const res = await axios.get( .... )
dispatch({ type: CLEAR, payload: res });
};