1

天气.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} 时出现问题显示数据,它一直给我一个指向温度的错误,说它没有定义,但它是数据的一部分

4

1 回答 1

5

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

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

<WeatherDisplay weather={weather}/>
于 2021-04-04T21:01:55.940 回答