javascript - 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
解决方案
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);
推荐阅读
- c - 查找数组中出现频率最高的数
- scala - 获取 Future[List[Future[T]]] 但需要 Future[List[T]] (丰富模式)
- postgresql - 将数据从 Postgresql 移动到 Redis(DB-1)
- sql-server - 尝试在 SQL SELECT 语句中使用 DATETIME
- seo - 站点地图索引是否应该包含扩展名为 .gz 的子站点地图?
- php - 将变量传递给wordpress中的高级自定义字段
- javascript - 无法读取未定义的属性“推送”如何解决?
- python - 在数据立方体中使用列表推导
- scala - 带有 uber-jar 的 Spark-submit 无法执行作业,没有任何输出或错误日志
- microsoft-cognitive - 使用 Microsoft 认知服务进行词形还原?