【问题标题】:Context returning undefined - useContext上下文返回未定义 - useContext
【发布时间】:2021-05-14 12:25:24
【问题描述】:

我正在尝试以最简单的方式设置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”添加到您的 App.js(或某些根组件)中
  • 太棒了!那就是我所缺少的。谢谢@Sumith

标签: javascript reactjs use-context


【解决方案1】:

答案:根组件上缺少Provider

【讨论】:

    【解决方案2】:

    嗨@cdgmachado:问题是由于创建上下文值时出现空值而不是使用此值:
    导出 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

    来自博客:这是讨论部分的截图:

    希望能解决

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-24
      • 2023-04-06
      • 2020-12-08
      • 2021-07-19
      • 2019-12-13
      • 2021-07-02
      相关资源
      最近更新 更多