我正在使用 React 创建天气应用程序,并且我有一个为我提供对象的 api
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>
);
}
}
获取数据后,我将数据存储为状态。 最后,我想将 this.state.weather.daily.data 作为 props 传递给子组件,但我收到了 TypeError: Cannot read property 'data' of undefined
最佳答案
<WeeklyWeather day={this.state.weather.daily.data} />
您可能会收到错误,因为在异步请求完成之前,没有初始化 this.state.weather.daily
。快速破解可能是这样的:
{ this.state.weather.daily && <WeeklyWeather day={this.state.weather.daily.data} />}
这将确保 WeeklyWeather
仅在初始化 daily
时呈现。
关于javascript - 将对象从 state 作为 props 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53804900/