React 子组件未呈现来自父组件值的 props。

3

我有一个简单的应用程序,调用天气API并将其显示在子组件中。

App.js

import './App.css';
import { useState, useEffect } from 'react'
import { Forecast } from './forecast'
import Card from './components/Card'

function App() {
  const apiURL = "https://weather.cc.api.here.com/weather/1.0/report.json?apiKey=XXXXX&product=forecast_7days&name=Berlin"
  const [weatherCards, setCards] = useState([])

  useEffect(() => {
    const getWeather = async() => {
      var forecastList = []
      const res = await fetch(apiURL)
      const data = await res.json()
      const forecasts = data.forecasts.forecastLocation.forecast
      for (let i = 0; i < 5; i++) {
        let iconLink = forecasts[i].iconLink
        let iconName = forecasts[i].iconName
        let utcTime = forecasts[i].utcTime
        let temperature = forecasts[i].temperature
        let forecast = new Forecast(iconLink, iconName, utcTime, temperature)
        forecastList.push(forecast)
        //console.log(forecastList)
      }
      setCards(forecastList)
    }
    getWeather()
  
  }, [])


  return (
    <div >
      <h1>My Weather dashboard</h1>
      <div className="container">
          <Card props={weatherCards[0]} />
      </div>
    </div>
  )
}
export default App;

Card.js

const Card = ( props ) => {
    return (
        <div className="card">
            <img src={props.iconLink}/>
            <div className="caption">{props.iconName}</div>
            <h3>Day: {props.day}</h3>
            <h3>time: {props.time}</h3>
            <h3>temperature: {props.temperature}</h3>
        </div>
    )
}

Forecast.js

export class Forecast {
    constructor(iconLink, iconName, utcTime, temperature) {
        this.iconLink = iconLink
        this.iconName = iconName
        this.utcTime = utcTime
        this.temperature =temperature
    }
}

然而,我的Card组件没有渲染Forecast对象属性。我不确定我做错了什么?代码看起来非常简单。

除了在初始(和任何后续)渲染时访问未定义的 X 之外,直到“weatherCards”状态被填充,还有什么问题吗?或者这就是问题所在? - Drew Reese
尽管我在UseEffect中设置了卡片状态,但无论等待多长时间,它都不会更新weatherCards变量。我希望在数据准备好时能够将props传递给Card组件。 - calveeen
let forecast = new Forecast(iconLink, iconName, utcTime, temperature) 是做什么的? - Drew Reese
它创建了一个新的Forecast类,我已经定义好了。我已经在帖子中进行了更新。 - calveeen
我认为Viet在下面已经给出了答案,但为什么不只是setCards(data.forecasts.forecastLocation.forecast.slice(0,5)),然后就可以结束了呢?for循环和Forecast类都是多余且不必要的。 - Drew Reese
我认为你是对的,那样会更好。我创建了一个预测类,因为并不是从API返回的所有对象属性都会被使用。 - calveeen
1个回答

4

你传递了名为props的props,所以你需要在Card组件中使用props.props.iconLink

或者你可以这样传递props:

<Card {...weatherCards[0]} />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接