You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在map遍历数组时获取外部数据的城市属性并传递给子组件

解决React中传递city属性给WeatherCard子组件的问题

看起来你已经离解决问题很近了!从你的代码和描述来看,weathers 对象应该是包含一个 city 属性(比如从OpenWeatherMap接口返回的格式,根节点就有城市信息),而不是每个 list 项里的 weather 对象包含城市数据。

具体步骤:

  1. 确认城市数据的位置:在你的 WeatherList 组件中,weathers 本身应该有 city 属性(你可以通过已有的 console.log(weathers) 来验证,应该能看到 city 对象,里面有 name 字段)。
  2. 传递city属性给WeatherCard:在循环渲染 WeatherCard 的时候,直接从 weathers 根对象中获取城市名称,作为 city props传递进去。
  3. 在WeatherCard中使用city属性:你已经在 WeatherCard 的props里声明了 city,现在可以把它渲染到组件的合适位置。

修改后的代码:

WeatherList组件(修改部分):

import React from 'react'
import { Col, Row } from 'react-bootstrap'
import WeatherCard from './WeatherCard'
const WeatherList = ({weathers}) => {
 console.log("weathers:")
 console.log(weathers)
 return (
  <Row>
   {weathers.list.map(({dt, main, weather}) => (
    <Col key={dt}>
     {/* 这里添加city属性,从weathers根对象获取 */}
     <WeatherCard 
       temp_max={main.temp_max} 
       temp_min={main.temp_min} 
       dt={dt * 1000} 
       main={weather[0].main} 
       icon={weather[0].icon} 
       city={weathers.city.name} // 新增这一行
     />
    </Col>
   ))}
  </Row>
 )
}
export default WeatherList;

WeatherCard组件(添加渲染city的部分):

// 若使用styled-components需提前导入:import styled from 'styled-components';
const WeatherCard = ({dt, temp_min, temp_max, main, icon, city }) => {
 const WeatherIcon = styled.div`color: whitesmoke;`;
 console.log("city:" + city)
 const refresh = () => {
  window.location.reload();
 }
 let weatherIcon = null;
 const date = new Date(dt);
 return (
  <div className="main">
   <Card style={{width: '18rem'}}>
    <Card.Img variant="top"
     src={`http://openweathermap.org/img/wn/${icon}@2x.png`}
    />
    <Card.Body>
     {/* 这里添加城市名称的显示 */}
     <Card.Subtitle className="mb-2 text-muted">{city}</Card.Subtitle>
     <Card.Title>{main}</Card.Title>
     <p>
      {date.toLocaleDateString()} - {date.toLocaleTimeString()}
     </p>
     <p>Min: {temp_min}</p>
     <p>Max: {temp_max}</p>
    </Card.Body>
   </Card>
  </div>
 );
};
export default WeatherCard;

为什么这样做?

因为OpenWeatherMap的5天预报接口返回的数据结构中,城市信息是在根层级的city字段,而不是每个预报项里的。所以你不需要从weather对象里找城市,而是直接从weathers根对象获取即可。

现在你应该能在WeatherCard的控制台输出里看到城市名称,并且在组件上显示出来了!

内容的提问来源于stack exchange,提问作者J.erome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:47:41