这是我下面的App.js,在获取数据和setState时 无法显示孩子的日期,但是获取了我的数据 控制台日志。甚至我在单独的文件中都有MyContext
// App.js
class MyProvider extends Component {
state = { userData: '' }
componentWillMount() {
fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(userData => {
this.setState({ userData: userData })
console.log('here is list =')
console.log(userData);
});
}
render() {
return (
<MyContext.Provider value={{ state: this.state }}>
{this.props.children}
</MyContext.Provider>
);
}
}
class App extends Component {
render() {
return (
<div>
<MyProvider value={{ state : this.state }}>
<Header />
<User />
</MyProvider>
</div>
);
}
}
export default App;
// User.js //无法显示性别,请在以下代码中发送电子邮件
class User extends Component {
render() {
return (
<div>
<MyContext.Consumer>
{
(context) => (
<React.Fragment>
<p>Gender : {context.state.gender}</p>
<p>Email : {context.state.email}</p>
</React.Fragment>
)
}
</MyContext.Consumer>
</div>
);
}
}
export default User;
答案 0 :(得分:0)
在上下文提供程序中,您正在将数据设置为userData
状态,因此您需要像context.state.userData.gender
这样在使用者中访问数据。同样,由于userData
是响应可用后的对象,因此您也应该在Provider构造函数中将其初始化为对象,否则您将需要在User
组件中添加检查,因为访问{{1} }来自userData
email and gender
User.js
class MyProvider extends Component {
state = { userData: {} }
componentWillMount() {
fetch('https://randomuser.me/api/')
.then(res => res.json())
.then(userData => {
this.setState({ userData: userData })
console.log('here is list =')
console.log(userData);
});
}
render() {
return (
<MyContext.Provider value={{ state: this.state }}>
{this.props.children}
</MyContext.Provider>
);
}
}
class App extends Component {
render() {
return (
<div>
<MyProvider value={{ state : this.state }}>
<Header />
<User />
</MyProvider>
</div>
);
}
}
export default App;