TypeError:无法读取未定义的属性(读取' data')这是由于我的使用情况而引起的吗?

发布于 2025-02-11 02:03:16 字数 1954 浏览 3 评论 0原文

尽管我的代码和测试运行良好,但我在终端中收到了这个错误:

src/components/Weather.tsx:31
    setWeather(response.data.result.weather);
                        ^

TypeError: Cannot read properties of undefined (reading 'data')
    at fetchWeatherData 

我在网上寻找了一些答案,而且大多数人似乎是错别字,但我认为这里并非如此。

这是我的组成部分:

import axios from 'axios';
import { useEffect, useState } from 'react';
import { IWeather } from '../interfaces/IWeather';
import { MdWbSunny } from 'react-icons/md';
import { IoIosPartlySunny } from 'react-icons/io';
import { BsFillCloudSnowFill } from 'react-icons/bs';
import { Title, Text } from '@mantine/core';

const Weather = () => {
  const [weather, setWeather] = useState<IWeather | null>();

  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather');
    setWeather(response.data.result.weather);
  };

  useEffect(() => {
    fetchWeatherData();
  }, []);

  return (
    <div className="container">
      <>
        <Title order={2}>
          {weather?.forcast === 'Sunny' ? (
            <MdWbSunny />
          ) : weather?.forcast === 'Snowing' ? (
            <BsFillCloudSnowFill />
          ) : (
            <IoIosPartlySunny />
          )}
        </Title>
      </>
      <Text size="xl">{weather?.forcast}</Text>
      <Text size="lg">Temp: {`${weather?.min} to ${weather?.max}`}</Text>
      <Text size="md">{weather?.description}</Text>
    </div>
  );
};

export default Weather;

错误是提及第31行。这是天气组件中的此块:

 <Title order={2}>
          {weather?.forcast === 'Sunny' ? (
            <MdWbSunny />
          ) : weather?.forcast === 'Snowing' ? (
            <BsFillCloudSnowFill />
          ) : (
            <IoIosPartlySunny />
          )}
        </Title>

I'm receiving this error in my terminal although my code and tests are running fine:

src/components/Weather.tsx:31
    setWeather(response.data.result.weather);
                        ^

TypeError: Cannot read properties of undefined (reading 'data')
    at fetchWeatherData 

I've looked for some answers online and it is quite broad most seem to be typos but I don't think that's the case here.

This is my component:

import axios from 'axios';
import { useEffect, useState } from 'react';
import { IWeather } from '../interfaces/IWeather';
import { MdWbSunny } from 'react-icons/md';
import { IoIosPartlySunny } from 'react-icons/io';
import { BsFillCloudSnowFill } from 'react-icons/bs';
import { Title, Text } from '@mantine/core';

const Weather = () => {
  const [weather, setWeather] = useState<IWeather | null>();

  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather');
    setWeather(response.data.result.weather);
  };

  useEffect(() => {
    fetchWeatherData();
  }, []);

  return (
    <div className="container">
      <>
        <Title order={2}>
          {weather?.forcast === 'Sunny' ? (
            <MdWbSunny />
          ) : weather?.forcast === 'Snowing' ? (
            <BsFillCloudSnowFill />
          ) : (
            <IoIosPartlySunny />
          )}
        </Title>
      </>
      <Text size="xl">{weather?.forcast}</Text>
      <Text size="lg">Temp: {`${weather?.min} to ${weather?.max}`}</Text>
      <Text size="md">{weather?.description}</Text>
    </div>
  );
};

export default Weather;

the error is mentioning line 31. Which is this block in the Weather component:

 <Title order={2}>
          {weather?.forcast === 'Sunny' ? (
            <MdWbSunny />
          ) : weather?.forcast === 'Snowing' ? (
            <BsFillCloudSnowFill />
          ) : (
            <IoIosPartlySunny />
          )}
        </Title>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

标点 2025-02-18 02:03:16

尝试像这样调试:

  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather', (request, response) => {
        console.log('request', request);
        console.log('response', response);
        setWeather(response.data.result.weather);
    });
    
  };

欢呼

Try to debug like so :

  const fetchWeatherData = async () => {
    const response = await axios.get('http://mock-api-call/weather/get-weather', (request, response) => {
        console.log('request', request);
        console.log('response', response);
        setWeather(response.data.result.weather);
    });
    
  };

Cheers

三人与歌 2025-02-18 02:03:16

似乎这不是有效的API URL,为了检测问题是什么,我想在获取函数中添加尝试/捕获块:

const fetchWeatherData = async () => {
    try {
      const response = await axios.get('http://mock-api-call/weather/get-weather');
     // Just put some log to ensure you have the response.
     const {data} = response;
     if (data?.result?.weather) {
        setWeather(data?.result?.weather);
      }
    } catch(error) {
      console.log("An Error is occured : ", error);
    }
  };

It seems like it's not a valid api url, in order to detect what the issue is , i would like to add try/catch block to the fetch function :

const fetchWeatherData = async () => {
    try {
      const response = await axios.get('http://mock-api-call/weather/get-weather');
     // Just put some log to ensure you have the response.
     const {data} = response;
     if (data?.result?.weather) {
        setWeather(data?.result?.weather);
      }
    } catch(error) {
      console.log("An Error is occured : ", error);
    }
  };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文