【问题标题】:React App is giving error when using context APIReact App 在使用上下文 API 时出错
【发布时间】:2021-02-06 17:52:04
【问题描述】:

我正在学习 React,现在尝试实现使用 Context API 的旧方式,但是当我尝试编译时出现错误。

上面写着:

TypeError: context is undefined. Version is 17.0.1

这是我使用的文件:

Test0.js

import React from 'react';
const Test0 = React.createContext();
export default Test0;

Test1.js

import React, { Component } from 'react';
import Test0 from './Test0';

class Test1 extends Component{
render(){
    return (
            <Test0.Consumer>
                {context => (<p>This is {context.name}</p> )}
            </Test0.Consumer>
        );
}
}
export default Test1;

Test2.js

import React, { Component } from 'react';
import Test0 from './Test0';
import Test1 from './Test1';

class Test2 extends Component{
state = {
    name: 'James',
    age : 30
}
render(){
    return (
        <Test0.Provider
            value={{
                name : this.state.name,
                age: this.state.age
            }}
        >
            <Test1 />
        </Test0.Provider>
        );
}
}

export default Test2;

然后我在 app.js

中渲染 &lt;Test1 /&gt;

【问题讨论】:

    标签: javascript reactjs react-context


    【解决方案1】:

    然后我在 app.js 中渲染

    您需要渲染Test2,因为您在那里定义了上下文提供程序。以下是完整工作代码的链接。

    CODESANDBOX 链接: https://codesandbox.io/s/context-api-issue-lqkv8

    【讨论】:

      【解决方案2】:

      您正在使用Test1 组件,该组件使用 Test0,一个上下文,您应该提供值,但在Test0 中您没有提供任何值。您错误地在单独的组件 Test2 中实现了提供程序,您没有渲染所以Test0 不知道提供的值,并且假设您没有定义上下文。

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 2018-08-23
        • 1970-01-01
        • 2018-01-14
        相关资源
        最近更新 更多