gpt4 book ai didi

reactjs - 如何从天气api中的日期检索数据?

转载 作者:行者123 更新时间:2023-12-05 06:24:09 25 4
gpt4 key购买 nike

我正在研究 Reactjs 天气项目并从 apixu.com 检索数据,其中包含当前和预报天气的所有详细信息。

我能够检索天气应用程序所需的几乎所有数据,日期除外,即从今天到 5 天的预报。我不知道如何获得日期,做了很多试验,但都是徒劳的。所以,一些解决方案是预期的。提前致谢。

  1. App.js

这段代码从api获取数据

const api_call2 = await fetch(`https://api.apixu.com/v1/forecast.json?` + 
`key=${API_KEY2}&q=${city}&days=5`);
const data2 = await api_call2.json();

这里的state设置为forecastdays

forecastdays: data2.forecast.forecastday

状态已定义

<ForecastDays forecastdays={forecastdays}/>
  1. index.js

这里通过 props 调用 forecastdays

export class ForecastDays extends Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
const { forecastdays} = this.props;
return (
<div>
{
forecastdays && forecastdays.map((day, idx) => {
return <WeatherForecast day={day.day} key={idx} />
})
},
{
forecastdays && forecastdays.map((date, idy) => {
return <WeatherForecast date={date.date} key={idy} />

})
}
</div>
)
}
}

这里你可以看到上面的day和date是WeatherForecast.js文件中映射和定义的2个参数

  1. WeatherForecast.js
export class WeatherForecast extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { day, date } = this.props;

// DATE first returns undefined and then loads data
console.log('DATE', date)

if(!day) return null;
return (
<div>
<MDBCardBody className="forecast-body">
<MDBCardHeader className="forecast-header">
<div className="inner-container">
<h2>{date}</h2> // Doesn't display date
<img src={day.condition.icon} />
<div className="text">{day.avgtemp_c}°C</div>
<div className="muted-text">{day.condition.text}</div>
</div>
</MDBCardHeader>

</MDBCardBody>
<br/>
</div>
)
}
}

export default WeatherForecast

I got the data within 'day' object but not in 'date'

1st picture -> Data from 'day' and 'date' is retrieved

 2nd picture -> Date returns undefined

最佳答案

当你为这个 forecastdays 数组迭代两次时,所以你可以迭代 single 并在 WeatherForecast 中传递你的 props 而不是迭代两次像下面的组件

forecastdays && forecastdays.map(o => <WeatherForecast day={o.day} date={o.date} />)

请检查下面的代码片段和工作stackblitz演示。

class ForecastDays extends Component {
constructor() {
super();
this.state = {
location:data.location.name,
forecastdays: data.forecast.forecastday
};
}
render() {
const {forecastdays} = this.state;
return (
<div>
<h1>City :- {this.state.location}</h1>
{
forecastdays && forecastdays.map(o => <WeatherForecast day={o.day} date={o.date} />)
}
</div>
);
}
}

关于reactjs - 如何从天气api中的日期检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57833663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com