你如何在React中显示来自api的数据?

Weather.JS 文件

import { useEffect, useState } from "react"
import axios from 'axios'
import WeatherDisplay from './WeatherDisplay'

const Weather = ({capital, params}) => {

const [weather,setWeather] = useState([])

useEffect(async () => {
    const result = await axios.get('http://api.weatherstack.com/current', {params})
      console.log(result.data)
      setWeather(result.data)
  },

[params])



return(
    <div>
        <h2>Weather in {capital}</h2>
        <WeatherDisplay current={weather.current}/>
    </div>
)
}
export default Weather

WeatherDisplay.js 文件

const WeatherDisplay = ({weather}) => {
  console.log(weather.current.temperature)
  return (
      <h1>{weather.current.temperature}</h1>
  )
}

export default WeatherDisplay

当我使用 {weather.current.temperature} 时出现数据显示问题,它不断给我一个指向温度的错误,说它没有定义,但它是数据的一部分

回答

weather.current作为道具传递。而子组件期望weather作为道具。所以,你最终做的是weather.current.current.temperature哪个是未定义的,因为它不存在。只需传递weather给 child 道具。

在调用子组件时进行此更改。

<WeatherDisplay weather={weather}/>

  • Or don't use `weather.current` in the component and just use `weather.tempreture` instead.

以上是你如何在React中显示来自api的数据?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>