gpt4 book ai didi

javascript - react 子组件不从父值渲染 Prop

转载 作者:行者123 更新时间:2023-12-04 13:07:30 25 4
gpt4 key购买 nike

我有一个简单的应用程序,它调用天气 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>
)
}

预测.js

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

但是,我的 Card 组件不呈现 Forecast 对象属性。我不确定我做错了什么?代码看起来非常简单。

最佳答案

您传递 Prop 名称 props 因此您需要在 Card 组件中使用 props.props.iconLink

或者你可以像这样传递 Prop :

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

关于javascript - react 子组件不从父值渲染 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68706105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com