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

How Do you display data from an api in React?

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 作为 prop。所以,你最终做的是 weather.current.current.temperature 这是未定义的,因为它不存在。只需将 weather 传递给子属性即可。

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

<WeatherDisplay weather={weather}/>