【问题标题】:Weather Api with React带有 React 的天气 API
【发布时间】:2020-12-05 11:08:24
【问题描述】:

我对 React 很陌生,所以我想有一个简单的问题。我正在尝试从 API 中获取天气描述,并据此尝试显示不同的图像。我写了一个函数 getForecast 并且 response.data.weather[0].description 变成了正确的值。因此,据此,我将“图像”分配给不同的 SVG,但不会右转。

import React, { useState } from 'react';
import axios from 'axios';
import './Products.css';
import ProductItem from './ProductItem';
import Weather from './Weather';
import { Container, Row, Col } from 'react-bootstrap';

function Products() {

  const [imageTemp, setImage] = useState('images/umbrella.svg');
  const getForecast = () => {

    axios({
      method: "GET",
      url: 'http://api.openweathermap.org/data/2.5/weather?q=Kaunas&appid=7e6e14c967d752abbafb23a1f251b21c'
    })
      .then((response) => {
        console.log(response.data.weather[0].description);
        if (response.data.weather[0].description === "overcast clouds") {
          setImage('images/umbrella.svg');
        }
        else if (response.data.weather[0].description === "clear") {
          setImage('images/sunglasses.svg');
        }
        else {
          setImage('images/snowflake.svg');
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  
  return (
    <div className='products'>
      <Container className="products-container">
        <h2 className="products__title">Products</h2>
        <h6 className="products__subtitle">Offers Today</h6>
        <Row>
          <Col xs="12" md="6" lg="6">
            <Weather
              src={imageTemp}
              path='/'
            />
          </Col>
          <Col xs="12" md="6" lg="6">
            <ProductItem
              src='images/img-2.jpg'
              text='The Best Coffee'
              path='/'
            />
            <ProductItem
              src='images/img-3.jpg'
              text='Top 100 Books'
              path='/'
            />
          </Col>
        </Row>
      </Container>
    </div>
  );
}

export default Products;

这是我的天气组件:

import React from 'react';

function Weather(props) {
    return (
        <div className='banner__item'>
            <figure className='banner__item__pic-wrap'>
                <img
                    className='banner__item__img'
                    src={props.src}
                />
            </figure>
        </div>
    );
}

export default Weather;

【问题讨论】:

  • 其中一个在您提出请求时是否有效?你测试了吗?也许有控制台日志?

标签: reactjs weather-api


【解决方案1】:

我认为在任何地方都没有对getForecast 的呼叫。

如果你想知道如何在你想要的时候调用该函数,我建议你详细查看useEffect钩子。

【讨论】:

    【解决方案2】:

    您必须使用useEffect 来调用此方法(getForecast)...将此部分添加到您的代码中

     useEffect(() => {
       getForecast();
      }, [imageTemp]);
    

    【讨论】:

    • 感谢您的快速回答,您的回答有效。
    猜你喜欢
    • 2021-05-08
    • 2011-01-04
    • 2014-06-20
    • 2015-11-02
    • 1970-01-01
    • 2018-09-11
    • 2011-12-09
    • 2011-11-15
    • 2013-07-06
    相关资源
    最近更新 更多