首页 > 解决方案 > TypeError:无法读取反应中未定义的属性'0'

问题描述

我正在开发天气应用程序。是学习项目。我收到错误。

我使用了 3 个组件。

应用程序.js:

<WeatherApiAddressProvider>
  <WeatherCity />
</WeatherApiAddressProvider>

WeatherApiAddressProvider(上下文 API):

const setApiAddress = (city) => {
  const address = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=7b7503a2aa9ca872738c7213619a72f5`;
  return address;
};

export const WeatherApiAddressProvider = ({ children }) => {
  return (
    <WeatherContext.Provider value={setApiAddress}>
      {children}
    </WeatherContext.Provider>
  );
};

WeatherCity.js

const setApiAddress = useContext(WeatherApiAddressContext);

const [city, setCity] = useState("");

const handleChange = (e) => {
  setCity(e.target.value);
};
return (
  <div>
    <div className="container">
      <div className="row">
        <div className="col">
          <select
            className="form-select mb-3"
            aria-label="Default select example"
            value={city}
            onChange={handleChange}
          >
            <option className="placeholder" value="">
              Please select a city
            </option>
            <option value="adana">Adana</option>
            ...
          </select>
        </div>

        <div className="col">
          <div className="p-5">
            <WeatherDetail setApiAddress={setApiAddress} city={city} />
          </div>
        </div>
      </div>
    </div>
  </div>
);

WeatherDetail.js

const [weatherInfo, setWeatherInfo] = useState({});

let imgCode = weatherInfo.weather[0].icon;

useEffect(() => {
  axios.get(city ? setApiAddress(city) : "").then((response) => {
    setWeatherInfo(response.data);
  });
}, [city, setApiAddress]);

return (
  <div>
    {city !== "" && (
      <div className="card">
        <img
          className="card-img-top"
          src={`https://openweathermap.org/img/wn/${imgCode}.png`}
        />
        <div className="card-body">
          <h5 className="card-title">{weatherInfo.name}</h5>
          <p className="card-text">
            Some quick example text to build on the card title and make up the
            bulk of the card's content.
          </p>
        </div>
      </div>
    )}
    {}
  </div>
);

如您所知,WeatherApiAddressProvider抛出setApiAddres函数,WeatherCity抛出城市变量。WeatherDetail使用 .接收这些并从 weatherapi 获取数据axios

我得到的错误:

TypeError:无法读取未定义的属性“0”(让 imgCode = weatherInfo.weather[0].icon)

我尝试过的解决方案:

我想在 WeatherDetail.js 中显示天气代表图像和天气详细信息。我怎样才能做到这一点?

标签: javascriptreactjsweather-api

解决方案


更改表达式如下WeatherDetails.js

  let imgCode = weatherInfo && weatherInfo.weather.length >0 && weatherInfo.weather[0].icon

推荐阅读