【问题标题】:dispatch is not accessible from useContext无法从 useContext 访问调度
【发布时间】:2021-04-07 05:01:26
【问题描述】:

我有一个简单的商店

import React, { createContext, useReducer } from "react";
import Reducer from "./UserReducer";

const initialState = {
    user: {},
    error: null
};

const Store = ({ children }) => {
    const [state, dispatch] = useReducer(Reducer, initialState);
    return (
        <Context.Provider value={[state, dispatch]}>
            {children}
        </Context.Provider>
    );
};

export const Context = createContext(initialState);
export default Store;

我已经用它包装了我的应用程序

<Store>
    <ThemeProvider theme={Theme}>
        <CssBaseline />
        <Navbar />
        <Wrapper>
            <Profile />
        </Wrapper>
    </ThemeProvider>{" "}
</Store>

还有一些额外的设置,我的身份验证页面位于单独的包装器中,所以我也用 store 包装了它。

这是该包装器的代码(额外删除)。

import Store from "../../../context/Store";
export default function Wrapper({ children }) {
    const classes = useStyles();
    return (
        <Store>
           //different dumb containers opening
                {children}
          //different dumb containers closing
        </Store>
    );
}

现在当我尝试访问子组件中的上下文时,例如

import React, { useContext } from "react";
import { Context } from "../../../context/Store";
import { SET_USER } from "../../../context/UserTypes";

function SignUp(props) {
    const [state, setState] = React.useState({ ...initialState });

    const [userData, dispatch] = useContext(Context);
    console.log(userData, dispatch, "check");
// rest of component

我收到以下错误

TypeError: undefined is not a function

我尝试在不解构的情况下记录 useContext 的结果,但它只有全局状态,但没有调度函数。

Reactjs 版本 = 17.0.1

更新:使用 Authenticator HOC 可以在外部访问调度,但不能在内部访问,因此这可能是放大问题。

我已经打开了放大回购的问题。

Unable to access dispatch from useContext from components wrapped withAuthenticator

【问题讨论】:

    标签: reactjs jsx aws-amplify context-api use-context


    【解决方案1】:

    我发现有几件事可能是潜在的问题。

    主要问题是您的Context 的值。创建上下文时,它的值是一个状态 (createContext(initialState))。但是,当您将 value 传递给 Context.Provider 时,您将给它一个包含状态和调度函数 (value={[state, dispatch]}) 的数组。您需要对上下文中包含的值保持一致。是状态对象还是元组?

    如果在Provider 之外访问Context,您所描述的错误似乎会发生什么。它会回退初始上下文值,该值只是一个状态,而不是 [state, dispatch] 元组。

    您需要将初始值更改为与您期望的值相匹配的值。

    const Context = createContext([
      initialState, // state
      () => console.error("Cannot dispatch because Context was used outside of a provider") // dispatch
    ]);
    

    但您还需要弄清楚为什么useContext 获取默认值而不是来自Provider 的值。我不确定接下来的两个问题是否能解决这个问题。

    看起来Profile 组件位于两个不同的Store 提供程序中。一个在一切之外,一个在Wrapper 组件内部。这些将有两个独立的状态实例。当同一上下文有两个提供者时,React 使用内部的提供者。因此,您从Profile 调度的任何操作都不会更新Store 的外部版本。

    您创建了Context 变量之后您在Store 组件中使用它。你应该换个顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-17
      • 2020-08-15
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多