繁体   English   中英

上下文返回未定义 - useContext

[英]Context returning undefined - useContext

我试图以最简单的方式设置useContext ,但它一直返回undefined

我已经检查了好几次,但仍然无法破译我错过了什么。

Context.js

import React from 'react';

export const Context = React.createContext();

export function Provider(props) {

    const sayHi = () => {
        console.log('hi')
    }

    const value = {
        actions: {
            sayHi
        }
    }

    return(
        <Context.Provider value={value}>
            {props.children}
        </Context.Provider>
    );
}

消费者组件( Transfer.js ):

import React, { useContext } from 'react';
import { Context } from '../Context';

function Transfer() {
    const value = useContext(Context);
    console.log(value); // ------> returns undefined
    console.log(Context); // ----> it is defined

    return (
        <div className="send">
            // some HTML
        </div>
    );
}


export default Transfer;

Folder structure

src
└───components
│   └─── Transfer.js
│  
└───App.js
└───App.scss
└───Context.js
    ...

答案:根组件上缺少Provider

嗨@cdgmachado:这个问题是由于创建上下文值时的空值而不是使用这个:
export const Context = React.createContext(null) 这是我读过的地方。 https://kentcdodds.com/blog/how-to-use-react-context-effectively 您也可以查看我的代码框: https://codesandbox.io/s/goofy-bash-z1cnq?file=/src/Context.js:28-76

来自博客:这是对讨论的部分的捕获:

在此处输入图像描述

希望它能解决它

暂无
暂无

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

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