【问题标题】:How to use data from a api (json) in react如何在反应中使用来自 api (json) 的数据
【发布时间】: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


    【解决方案1】:

    UseState() 是 react hook 方法,有助于实现。检查以下代码以供参考。

    import React, { useState } from 'react';
    
    
    const Forecast = () => {
        const [forecast, setForecast] = useState();
        function getForecast() {
            return fetch("https://data.buienradar.nl/2.0/feed/json")
            .then((response)=> response.json())
            .then((data) => {return setForecast(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:  {forecast}</p>
            </div>
        )
    }
    
    export default Forecast;
    

    【讨论】:

      猜你喜欢
      • 2019-04-26
      • 1970-01-01
      • 2017-01-31
      • 2020-04-23
      • 2018-02-18
      • 2017-11-26
      • 2022-10-25
      • 2016-02-04
      • 2019-08-21
      相关资源
      最近更新 更多