useContext从A

问题描述

我正在尝试使用useContext将数据从JSON文件传递到组件:

import sessionData from '../session.json';

import React from 'react';

export const SessionContext = React.createContext(sessionData);

export const SessionProvider = SessionContext.Provider;
export const SessionConsumer = SessionContext.Consumer;

console.log('session data',sessionData); //console log ok

接下来,我将其传递给类组件

  static contextType = SessionContext;

  componentDidMount() {
    const sessId = this.context;
    console.log('steps',sessId); // log ok
  }


  render() {
         return <SessionProvider value={sessId}> //value returns undefined.
                    <Child A />
                    <Child B />
                    <Child C />
               </SessionProvider>;
         }

在所示的前两个代码块中,我的数据返回正常。现在,我想将其传递给子组件(它们是功能组件)。但是,当我尝试将值传递给会话提供者<SessionProvider value={sessId}时,该值将返回未定义的值。

我还看到了其他示例,该示例将值直接传递给所有子组件都可用的{sessId.name} . However,if I'm just trying to make sessId``之类的组件。

解决方法

sessId不存在

您收到的错误很可能是sessId不存在。

sessId存在于componentDidMount方法中,但不存在于您的渲染方法中。

您需要使用this.context在渲染方法中创建该变量,就像在componentDidMount中所做的一样。

您不需要提供程序

但是...您不需要那里的提供者。当您向React.createContext提供初始值时,该值将成为默认值,因此您可以将其与子项一起使用,数据就在那里。

您不需要上下文

但是,如果您只使用静态JSON,则根本不需要上下文:只需将JSON文件导入每个子级中,然后在其中使用它即可。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...