简体   繁体   English

反应上下文返回未定义

[英]React context returns undefined

I want to use context in React to pass authentication information to child components. 我想在React中使用上下文将身份验证信息传递给子组件。 My context provider is in a file named AuthContext.js : 我的上下文提供程序位于一个名为AuthContext.js的文件中:

import React, { Component, createContext } from 'react';

export const AuthContext = createContext();

class AuthContextProvider extends Component {
    state = {
        isAuthenticated: false
    };
    toggleAuth = () => {
        this.setState({ isAuthenticated: !this.state.isAuthenticated });
    };
    render() {
        return (
            <AuthContext.Provider value={{...this.state, toggleAuth: this.toggleAuth}}>
                {this.props.children}
            </AuthContext.Provider>
        );
    }
}

export default AuthContextProvider;

But when I'm accesing the context from the child components, it returns undefined 但是当我从子组件访问上下文时,它返回undefined

import { AuthContext } from "../contexts/AuthContext";

export default function ButtonAppBar() {
    return(
        <AuthContext.Consumer>{(authContext) => {
            console.log(authContext);
        }}</AuthContext.Consumer>
    );
}

After checking the React Developer Tools, I came to see that ButtonAppBar is not inside AuthContextProvider . 检查React开发工具后,我发现ButtonAppBar不在AuthContextProvider Imports are correct. 导入是正确的。 Any reason for this apart from import errors? 除了导入错误外,还有其他原因吗?

react开发人员工具的屏幕截图

React version: 16.9.0 反应版本: 16.9.0

If you take a look at this working codesandbox you will see that your code is correct and should be working if you did everything all right. 如果您查看此工作代码和框,您会发现您的代码是正确的,并且在一切正常的情况下应该可以正常工作。

Reasons that can make it not work 使其无法工作的原因

  • Maybe you are importing it wrong? 也许您输入的是错误的? Please check how you import it. 请检查您如何导入。
  • Maybe ButtonAppBar isn't inside AuthContextProvider . 也许ButtonAppBar不在AuthContextProvider

For the context to work, the consumer needs to be inside of the provider. 为了使上下文起作用,消费者需要位于提供者内部。

This will work 这会起作用

  <AuthContextProvider>
    <ButtonAppBar /> {// consumer inside the provider }
  </AuthContextProvider>

This will not work 这行不通

  <AuthContextProvider>
      ...
  </AuthContextProvider>
  <ButtonAppBar /> {// consumer outside the provider }

In the screenshot from the question, you don't have AuthContextProvider wrapping the routes, so you will never be able to get the context. 在问题的屏幕截图中,您没有AuthContextProvider包装路径,因此您将永远无法获取上下文。

You didn't provided the code correctly but I'm guessing that what you need to do is 您没有正确提供代码,但我猜您需要做的是

<App>
    <AuthContextProvider> {// AuthContextProvider wrapping routes so you can get the context}
        <BrowserRouter>
            ...
        </BrowserRouter>
    </AuthContextProvider>
</App>

Closures my friend. 关闭我的朋友。 Your child component is executing an anónimo us function and that callback is been executed by the browser, if you console.log this you'll see that this is window and as you can imagine window does not have that function 您的子组件正在执行anónimous函数,并且该回调已由浏览器执行,如果您在console.log上登录,则会看到这是窗口,并且您可以想象window没有该功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM