reactjs - While using React Context API ,unable to fetch data
问题描述
This is my App.js , I am using context api but I am unable to fetch data at {context.country} and {context.job} which is in child component i.e Neighbour. This is my App.js , I am using context api but I am unable to fetch data at {context.country} and {context.job} which is in child component i.e Neighbour. App.js
import React, { Component } from 'react';
import Neighbour from './Neighbour';
const MyContext = React.createContext();
class MyProvider extends Component {
state = {
firstName: 'Tom', lastName: 'Holland', age: 24, country: 'America', job: 'Actor',
}
render() {
return (
<MyContext.Provider value={{
state: this.state, growOld: () => this.setState({ age: this.state.age + 1 })
}}>
{this.props.children}
</MyContext.Provider>
);
}
}
class App extends Component {
render() {
return (
<div className="App">
<MyProvider value={{ state: this.state }}>
<div>
<p>I am in App component</p>
<Family />
<br />
<Neighbour />
</div>
</MyProvider>
</div>
);
}
}
export default App;
Neighbour.js
import React, { Component } from 'react';
const MyContext = React.createContext();
class Neighbour extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<MyContext.Consumer>
{context => (
<React.Fragment>
<p>Country : {context.country}</p>
<p>Job : {context.job}</p>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
);
}
}
export default Neighbour;
解决方案
Since you are providing the value as object {state: this.state}
to context, you need to use it like context.state.country
in your consumer.
<MyContext.Consumer>
{context => (
<React.Fragment>
<p>Country : {context.state.country}</p>
<p>Job : {context.state.job}</p>
</React.Fragment>
)}
</MyContext.Consumer>
or you Provide the value in provider like
<MyProvider value={this.state}>
<div>
<p>I am in App component</p>
<Family />
<br />
<Neighbour />
</div>
</MyProvider>
Also in Neighbour
component you re creating a context again which doesn't have a Provider
and hence the value in Consumer would come undefined, you need to import the same context that you have used the Provider
on
In Neighbour.js
Neighbour.js
import React, { Component } from 'react';
inport { MyContext } from 'path/to/context';
推荐阅读
- java - Java如何比较字符串,字符串比较问题
- asp.net - 在 asp.net Core Web 应用程序中包含 App.config 文件
- node.js - 在角度中,如何将不同的 FormGroup 动态添加到 FormArray 中?
- python - Python:如何使用正则表达式仅选择括号内的某些整数
- javascript - 图像存储在本地并预加载,但加载速度仍然很慢
- numpy - 在基于 ARM 处理器 32 位的 Ubuntu 操作系统上安装机器学习包
- r - 如何将元素与嵌套向量列匹配?
- excel - 了解 If Err.Number 的使用
- c# - 我无法使用 HttpClientMultipartFormDataContent 模拟 HTML 表单帖子
- tensorflow - tensorflowjs 的 WebGL 后端很晚才加载模型(blazeface)