【问题标题】:Update context from another context in reactjs从 reactjs 中的另一个上下文更新上下文
【发布时间】: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


    【解决方案1】:

    没关系,你在应用中有多少上下文,只要你的提供者在层次结构中更高,你总是可以定位正确的上下文

    例如,如果AlertContextProvider 包装了调用 getErrors 的组件,那么您绝对可以定位警报

    假设MyComponent 调用getErrorsAlerts 组件是提供者,你的结构将是

    <App>
       <Alerts>
          <MyComponent />
       </Alerts>
    </App>
    

    现在在 myComponent 中你需要使用 useContext 和 AlertContext 然后调用 dispatch

    const [data, dispatch] = useContext(AlertContext);
    
    const getErrors = async () => {
        const res = await axios.get( .... ) 
        dispatch({ type: CLEAR, payload: res });
      };
    

    【讨论】:

    • 问题是 getErrors 在另一个上下文中,我们称它为“MyComponentContext” 我想要的是一个清晰的方式让这个上下文与 alertContext “联系”......因为动作是异步的而且我不想在组件中等待...(这将访问两个上下文)
    • 您可以使用 AlertContext 包装您的应用程序,以便您可以在任何地方使用它,因为除非您在层次结构中有提供程序,否则您无法访问该上下文值
    • 我们的解决方案是用 useReducerWithExtras 包装 useReducer,然后在其中使用警报上下文。
    猜你喜欢
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多