简体   繁体   English

React Context Provider没有传递值

[英]React Context Provider is not passing the values

I am just starting to learn Context and following a tutorial. 我刚刚开始学习Context,并正在学习教程。 Did exactly what Wes Bos did but still the state is not getting passed as expected to the Consumer. 确实做到了韦斯·波斯(Wes Bos)的所作所为,但仍然没有如预期般将状态传递给消费者。

TypeError: Cannot read property 'name' of undefined this error occurs TypeError: Cannot read property 'name' of undefined会发生此错误

Already tried making functional components but the same thing happens 已经尝试制造功能组件,但发生了同样的事情

The Context component: 上下文组件:

import React, {Component} from 'react';

const MyContext = React.createContext();
export default class MyProvider extends Component {
    state = {
        name: "John Doe",
        age: 23,
    };

    render() {
        return (
            <MyContext.Provider value={this.state}>
                {this.props.children}
            </MyContext.Provider>
        )
    }
}

export const Consumer = MyContext.Consumer;

And the Person Component: 和人员组成部分:

import React, {Component} from 'react';
import {Consumer} from '../Context.js'
export default class Person extends Component {
    render() {
        return (
                <Consumer>
                    {
                        (value) => {
                            return (
                                <React.Fragment>
                                    <p>I am inside the consumer {value.name} </p>
                                </React.Fragment>
                            )
                        }
                    }
                </Consumer>
        );
    }
}


The expected output should be I am inside the Consumer John Doe 预期的输出应该是I am inside the Consumer John Doe

The error is this : TypeError: Cannot read property 'name' of undefined 错误是这样的: TypeError: Cannot read property 'name' of undefined

The problem seems to be you're not actually calling the context provider component with the MyContext.Provider anywhere in your code. 问题似乎是您实际上MyContext.Provider在代码中的任何位置使用MyContext.Provider调用上下文提供程序组件。

I made a working example: https://codesandbox.io/s/sweet-dust-195sh 我做了一个工作的例子: https : //codesandbox.io/s/sweet-dust-195sh

Here's another working example with your code: https://codesandbox.io/s/vigorous-monad-hecom 这是您的代码的另一个工作示例: https : //codesandbox.io/s/vigorous-monad-hecom

You forgot to call the MyContext component, as you need to pass the consumer children to it. 您忘记了调用MyContext组件,因为您需要将消费者子代传递给它。

import React from "react";
import ReactDOM from "react-dom";
import MyContext from "./MyContext";
import Person from "./Person";
import "./styles.css";

function App() {
  return (
    <div className="App">
      <MyContext>
        <Person />
      </MyContext>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

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

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