【发布时间】:2019-05-17 05:03:18
【问题描述】:
我正在使用 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
【问题讨论】:
-
你需要使用
setState来更新初始状态(不是this.state.weather = {.......})。能发下相关代码吗? -
好的,给我3分钟,我会提供完整代码
标签: javascript reactjs state