在openweathermap API中使用天气图标时如何消除浏览器404错误?

问题描述 投票:0回答:0

browser error 404 and well-rendered clouds icon image

我正在用 React Native 制作天气应用程序。 即使我从 openweathermap 图像链接正确获取天气图像(云图标),我仍然连续遇到此 404 错误。

我从 openweathermap API 获取天气图标的代码在这里。

import { useEffect, useState } from 'react';
import { axiosClient } from 'api/axiosClient';
import { UNITS } from 'api/const';
import { useGeolocation } from './useGeolocation';
import { WeatherType } from 'types/weatherType';

const defaultWeatherData = {
  ... // omit
  weatherIcon: '',
};

export const useWeather = () => {
  const [weatherData, setWeatherData] =
    useState<WeatherType>(defaultWeatherData);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      const { lat, lon } = await useGeolocation();

      try {
        const { data: weatherData } = await axiosClient.get(
          `/data/2.5/weather?lat=${lat}&lon=${lon}&units=${UNITS}&appid=${process.env.API_KEY}`
        );

        setWeatherData({
          ... // omit
          weatherIcon: weatherData.weather[0].icon || '01d', // '01d' is equal to 'Sunny' Icon. I put this as a default of weatherIcon property.
        });
      } catch (err: any) {
        setError(err);
        console.log(err);
      } finally {
        setIsLoading(false);
      }
    };

    if (isLoading) {
      fetchData();
    }
  }, []);

  return [weatherData, isLoading, error] as [WeatherType, boolean, any];
};

这是 App.tsx.

import { StyleSheet, Text, View, StatusBar, Image } from 'react-native';
import { Date, Icon, Const } from './utils';
import { COLOR } from './styles/color';
import { useWeather } from 'hooks/useWeather';

export default function App() {
  const [weatherData, isLoading, error] = useWeather();

  const {
    weatherIcon,
    ... // omit
  } = weatherData;

  const weatherIconUrl = `https://openweathermap.org/img/w/${weatherIcon}.png`;

  return (
    ...
    <View style={styles.main}>
      <Text style={styles.temp}>{temp}°</Text>
      <Text style={styles.weather}>{weather}</Text>
      <Image
        source={{ uri: weatherIconUrl }} // Here!
        style={{ width: 50, height: 50 }}
      />
    </View>
    ...
  );

weatherIcon 在浏览器视图中呈现得很好。但是我在浏览器控制台中反复出现 404 错误。

我原以为当图标呈现良好时,404 错误就会消失。我该怎么办?

react-native http-status-code-404 openweathermap
© www.soinside.com 2019 - 2024. All rights reserved.