【发布时间】:2021-08-29 00:54:49
【问题描述】:
我正在使用 react 和 typescript 制作一个简单的天气应用程序。
我想知道如何在 react 和 typescript 中显示从公共 api 获取的简单数据。这个 api 是 json 格式的。网址(https://data.buienradar.nl/2.0/feed/json)
如何在 react 中使用 api 数据? 我尝试的是在段落中调用获取预测函数。
<p>Forecast: {getForecast} </p>
预测组件的源代码。
import React from 'react';
const Forecast = () => {
function getForecast() {
return fetch("https://data.buienradar.nl/2.0/feed/json")
.then((response)=> response.json())
.then((data) => {return data.forecast})
// .then((data) => {return data});
.catch((error) => {
console.log(error)
})
}
return (
<div>
<h2>Take weatherdata from the api</h2>
<div>
</div>
<button onClick={getForecast}>Take weather data from the api</button>
<p>Forecast: {getForecast}</p>
</div>
)
}
export default Forecast;
【问题讨论】:
标签: json reactjs typescript