首页 > 解决方案 > React Context Provider is not passing the values

问题描述

I am just starting to learn Context and following a tutorial. Did exactly what Wes Bos did but still the state is not getting passed as expected to the Consumer.

TypeError: Cannot read property 'name' of undefined this error occurs

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

The error is this : TypeError: Cannot read property 'name' of undefined

标签: javascriptreactjs

解决方案


The problem seems to be you're not actually calling the context provider component with the MyContext.Provider anywhere in your code.

I made a working example: https://codesandbox.io/s/sweet-dust-195sh

Here's another working example with your code: https://codesandbox.io/s/vigorous-monad-hecom

You forgot to call the MyContext component, as you need to pass the consumer children to it.

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);

推荐阅读