Javascript 将对象作为道具从状态传递到子组件
我正在用React创建天气应用程序,我有一个api为我提供对象Javascript 将对象作为道具从状态传递到子组件,javascript,reactjs,state,Javascript,Reactjs,State,我正在用React创建天气应用程序,我有一个api为我提供对象 import React, { Component } from 'react'; import WeeklyWeather from './components/WeeklyWeather'; const api = ''; class App extends Component { constructor() { super(); this.state = { weather: {} }
import React, { Component } from 'react';
import WeeklyWeather from './components/WeeklyWeather';
const api = '';
class App extends Component {
constructor() {
super();
this.state = {
weather: {}
}
}
componentDidMount() {
fetch(api)
.then(response => response.json())
.then(data => this.setState({ weather: data }));
}
render() {
return (
<div className="App">
<WeeklyWeather day={this.state.weather.daily.data} />
</div>
);
}
}
import React,{Component}来自'React';
从“./components/WeeklyWeather”导入WeeklyWeather;
常量api=“”;
类应用程序扩展组件{
构造函数(){
超级();
此.state={
天气:{}
}
}
componentDidMount(){
获取(api)
.then(response=>response.json())
.then(data=>this.setState({weather:data}));
}
render(){
返回(
);
}
}
获取数据后,我将数据存储为状态。
最后,我想将this.state.weather.daily.data作为道具传递给子组件,但我收到了TypeError:无法读取未定义的第一次渲染的属性“data”this.state.weather尚未初始化 沿着这条线走
类应用程序扩展组件{
构造函数(){
超级()
此.state={
天气:{}
}
}
组件安装(){
获取(代理)
.then(response=>response.json())
.then(data=>this.setState({weather:data}))
}
渲染(){
返回(
{this.state.weather&&(
)}
)
}
}
这将确保仅在初始化
每日时才渲染周天气。在道具存在之前将道具传递给子道具
一旦HTML绑定到DOM,就会调用componentDidMount()
,这意味着您的render()
已经运行。但是,当然,您的render()
引用了this.state.weather.daily.data
,它在componentDidMount()
完成之前不存在
您所要做的就是在尝试使用数据之前检查数据是否已加载
<WeeklyWeather day={this.state.weather.daily && this.state.weather.daily.data} />
您需要使用setState
更新初始状态(而不是this.state.weather={……}
)。你能发布相关代码吗?好的,给我3分钟,我会提供完整的代码我们现在开始投票真的吗?伊兰汉堡,乔治
<WeeklyWeather day={this.state.weather.daily.data} />
{ this.state.weather.daily && <WeeklyWeather day={this.state.weather.daily.data} />}
<WeeklyWeather day={this.state.weather.daily && this.state.weather.daily.data} />