【问题标题】:Is there a way to map over the cities on my cities array using the api and rendering the info from all cities on the array?有没有办法使用 api 映射我的城市阵列上的城市并渲染来自阵列上所有城市的信息?
【发布时间】:2019-01-12 02:58:06
【问题描述】:

现在只显示第一项的信息。 我将要从中获取信息的城市存储在常量中,现在我 我正在尝试从每个人那里获取信息以显示。 我不知道该怎么做。

class HomePage extends Component {
  state = {
    weatherResults: []
  };

  componentDidMount() {
    const cities = ["Boston", "New York"];

    fetch(`http://api.openweathermap.org/data/2.5/forecast?id=52490&units=imperial&appid=${API_KEY}&q=${cities}&cnt=60`)
      .then(res => res.json())
      .then(results => {
        this.setState({
          weatherResults: results
        });
        console.log(results);
      })
      .catch(error => console.error(error));
  }

  render() {
    const { weatherResults } = this.state;
    return (
      <div>
        {this.state.weatherResults.length !== 0 && (
          <div className="container" key={weatherResults.city.id}>
            <h2> {weatherResults.city.name} </h2>
            <p> {weatherResults.list[0].main.temp}</p>
            <p>{weatherResults.list[0].weather[0].description}</p>
            <p>
              Humidity:
              {weatherResults.list[0].main.humidity}
            </p>
            <p> Wind: {weatherResults.list[0].wind.speed} </p>
          </div>
        )}
      </div>
    );
  }
}

export default HomePage;

【问题讨论】:

    标签: reactjs api


    【解决方案1】:

    您可以为每个城市创建一个单独的fetch 请求,并使用Promise.all 将两个请求的结果置于两个请求都完成后的状态。

    然后您可以在 weatherResults 数组上使用 map 在 render 方法中显示两个城市的信息。

    示例

    class HomePage extends Component {
      state = {
        weatherResults: []
      };
    
      componentDidMount() {
        const cities = ["Boston", "New York"];
    
        const promises = cities.map(city => {
          return fetch(`http://api.openweathermap.org/data/2.5/forecast?id=52490&units=imperial&appid=${API_KEY}&q=${city}&cnt=60`)
            .then(res => res.json());
        });
    
        Promise.all(promises)
          .then(weatherResults => {
            this.setState({ weatherResults });
          })
          .catch(error => console.error(error));
      }
    
      render() {
        const { weatherResults } = this.state;
    
        if (weatherResults.length === 0) {
          return null;
        }
    
        return (
          <div className="container">
            {weatherResults.map(weatherResult => (
              <div key={weatherResult.city.id}>
                <h2>{weatherResult.city.name}</h2>
                <p>{weatherResult.list[0].main.temp}</p>
                <p>{weatherResult.list[0].weather[0].description}</p>
                <p>Humidity: {weatherResult.list[0].main.humidity}</p>
                <p>Wind: {weatherResult.list[0].wind.speed}</p>
              </div>
            ))}
          </div>
        );
      }
    }
    

    【讨论】:

    • 再次感谢 Tholle !这非常有帮助,但我正在尝试让 api 为波士顿市和纽约市呈现此信息。你知道这是否可能吗?
    • @AngieSpears 不客气!啊,我想我误解了这个问题。我更新了答案。
    • 谢谢托勒!我是新手,所以我可能没有正确询问!这是有道理的!
    【解决方案2】:

    你可以这样做。

    render() {
      const { weatherResults } = this.state;
         return (
             <div>
                 { this.state.weatherResults.length &&
                 <div className = "container">
                   <h2> { weatherResults.city.name}  </h2>
                 </div>
                 }
             { 
              this.state.weatherResults.list.map((ele, idx) => (
                  <div>
                   <p> {ele.main.temp}</p>
                   <p> 
                     {ele.weather[0].description} 
                  </p>
                  <p> Humidity: 
                     {ele.main.humidity} </p>
                 <p> Wind: {ele.wind.speed} </p>
             </div>
              ))
            }
          </div>
         );
       }
      }
    

    基本上我在上面所做的是创建一个反应组件数组并根据列表中的内容显示它们。现在我不能 100% 确定你的 JSON 结构是什么样的,所以我只是根据你上面发布的代码做出假设。

    如果可能,id 将所有与 JSON 相关的内容移动到 map 函数中。

    这部分:

    { this.state.weatherResults.length &&
             <div className = "container">
               <h2> { weatherResults.city.name}  </h2>
             </div>
             }
    

    还建议数组/映射调用中的每个元素都有自己的唯一键,而不是索引。因此,如果 JSON 包含一些唯一标识符,例如数据库中的主键,请使用它。

    【讨论】:

    • 您好 Joshua,感谢您的帮助!那么我是否需要为城市数组加上日期才能完成这项工作?
    • 不确定您所说的“未注明日期的城市数组”是什么意思
    • 我实际上是在尝试使用天气 api 从几个城市提取信息。因此,我创建了一个名为 citys 的常量,其中包含我想从中获取信息的城市数组。如果我仍然没有意义,我深表歉意,我是新手...再次感谢您的帮助!
    • 没问题,尽我所能提供帮助。由于我不熟悉您使用的 api,所以在查询 JSON 中的两个城市后,我有几个问题,您是否发现波士顿与纽约有什么区别?
    【解决方案3】:

    要在 React 中渲染 Array 中的项目,您应该使用 Array.prototype.map()

    例如:

      render() {
        const { weatherResults } = this.state;
        return (
          <div>
            {
              weatherResults.list.length > 0 && 
              weatherResults.list.map(item => (
                <div className="container" key={weatherResults.city.id}>
                  <h2> {item.city.name} </h2>
                  <p> {item.main.temp}</p>
                  <p>{item.weather[0].description}</p>
                  <p>Humidity: {item.main.humidity}</p>
                  <p> Wind: {item.wind.speed} </p>
                </div>
             ));
           }
          </div>
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多