不能从useContext访问调度 [英] dispatch is not accessible from useContext

查看:99
本文介绍了不能从useContext访问调度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的商店

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;

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

i have wrapped my app with it like

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

还有其他设置,我的身份验证页面位于单独的包装中,因此我也将其与商店一起包装了.

There is additional setup as well where my authentication pages are located in separate wrapper so i wrapped that with store as well.

这是该包装程序的代码(已删除).

here is code for that wrapper (extra removed).

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>
    );
}

现在,当我尝试访问子组件之类的上下文时

Now when i try to access context within child component like

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的结果而不破坏其结构,但是它只有全局状态,但是没有调度功能.

i tried to log result of useContext without destructuring it but all it had was global state but no dispatch function with it.

Reactjs版本= 17.0.1

Reactjs version = 17.0.1

更新:可以在Authenticator HOC外部访问分派,但不能在其中访问,因此这可能是放大问题.

Update: dispatch is accessible outside withAuthenticator HOC but not within that so it might be amplify issue.

我已经打开了关于扩增回购的问题.

i have opened issue on amplify repo.

无法从使用Authorenticator包装的组件的useContext中访问分派

推荐答案

我认为有些事情可能是潜在的问题.

There a few things I see that could be potential issues.

主要问题是您的Context的价值.创建上下文时,其值为状态(createContext(initialState)).但是,当您将value传递给Context.Provider时,将为其提供一个既包含状态又包含分派函数(value={[state, dispatch]})的数组.您需要对上下文中包含的值保持一致.是状态对象还是元组?

The major problem is the value of your Context. When you create the context, its value is a state (createContext(initialState)). But when you pass a value to the Context.Provider you are giving it an array which contains both a state and a dispatch function (value={[state, dispatch]}). You need to be consistent about the value that is contained in the context. Is it a state object or a tuple?

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

The error that you are describing seems like what would happen if the Context is accessed outside of a Provider. It would fall back the initial context value which is just a state rather than a [state, dispatch] tuple.

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

You need to change the initial value to something that matches the value that you are expecting.

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

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

But you also need to figure out why the useContext is getting the default value instead of one from a Provider. I'm not sure if these next two issues will fix that or not.

看起来Profile组件位于两个不同的Store提供程序内部.一种在所有内容之外,另一种在Wrapper组件内部.这些将具有两个单独的状态实例.当同一上下文有两个提供者时,React使用内部提供者.因此,您从Profile分派的任何操作都不会更新Store的外部版本.

It looks like the Profile component is inside of two different Store providers. One which is outside of everything and one which is inside of the Wrapper component. These will have two separate instances of state. When there are two providers for the same context React uses the inner one. So any actions that you dispatch from Profile won't update the outer version of Store.

Store组件中使用它后,创建Context变量 .您应该切换顺序.

You create the Context variable after you use it in your Store component. You should switch the order.

这篇关于不能从useContext访问调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆