redux 错误无法读取未定义(阅读“temp”)的属性类型错误:无法读取未定义的属性(阅读“temp”)

irlmq6kh  于 2023-03-18  发布在  其他
关注(0)|答案(1)|浏览(204)

这是我的代码(reactredux-toolkit),我得到了那个错误。

import { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import styles from "./styles.module.css";
import { getCurrentWeather } from "../../Redux/Reducers/currentWeatherSlice";
import { getUserPosition } from "../../Redux/Reducers/userPositionSlice";

// URLFor the icons
// https://openweathermap.org/img/wn/${}.pngs

function CurrentWeather() {
  const dispatch = useDispatch();
  const currentWeather = useSelector(
    (state) => state.currentWeather.currentWeather
  );
  const userPosition = useSelector((state) => state.userPosition.userPosition);

  const [query, setQuery] = useState("");
  const [x, setX] = useState(null);
  const [y, setY] = useState(null);

  //Get user's Position
  useEffect(() => {
    const successHandler = (position) => {
      setX(position.coords.latitude);
      setY(position.coords.longitude);
    };
    navigator.geolocation.getCurrentPosition(successHandler);

    if (x && y !== null) {
      dispatch(getUserPosition({ x, y }));
    }
  }, [dispatch, x, y]);

  const handleCitySearch = (e) => {
    setQuery(e.target.value);
  };

  const handleForm = (e) => {
    e.preventDefault();
  };

  const handleCityFetch = () => {
    dispatch(getCurrentWeather(query));
    setQuery("");
  };

  console.log(userPosition);

  return (
    <div className={styles.container}>
      <h1>CurrentWeather</h1>
      <div className={styles.currentWeather_container}>
        <div className={styles.input_container}>
          <form onSubmit={handleForm} className={styles.form}>
            <input
              value={query}
              type="text"
              placeholder="Search City"
              onChange={handleCitySearch}
            />
            <button onClick={handleCityFetch}>Go</button>
          </form>
        </div>

        <div className={styles.top_section}>
          {x && y && userPosition && (
            <>
              <div>
                <p>{userPosition.name}</p>
                <p>{userPosition.visibility}</p>
              </div>
              <div>
                <span>{userPosition?.main.temp}</span>
                <span>°C</span>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default CurrentWeather;

即使它在userPosition.name上按预期工作,当我试图渲染userPosition.main.temp时,我还是得到了错误。
我不确定这是redux状态问题,还是我试图在获得数据之前进行渲染(尽管看起来我确实拥有数据)。
我已经尝试了多种解决方案,如将userPosition的状态移动到它自己的切片,在userPosition上使用可选链操作符,而且我到处都有一堆控制台日志,但我找不到我的错误。

2hh7jdfx

2hh7jdfx1#

您对错误的对象进行了空检查。错误是通知您userPosition.main未定义。但此访问是正常的,与userPosition.nameuserPosition.visibility相同。由于定义了userPosition,因此不会引发错误。当userPosition.main未定义且代码尝试访问temp属性时,会出现此问题

{x && y && userPosition && (
  <>
    <div>
      <p>{userPosition.name}</p>       // ok, value is undefined
      <p>{userPosition.visibility}</p> // ok, value is undefined
    </div>
    <div>
      <span>
        {userPosition?.main.temp}  // not ok, accessing undefined object
      </span>
      <span>°C</span>
    </div>
  </>
)}

由于代码已经在上面进行了检查,以确保userPosition是真实的,因此将空检查移到可能为空/未定义的main属性上。

{x && y && userPosition && (
  <>
    <div>
      <p>{userPosition.name}</p>       // ok, value is undefined
      <p>{userPosition.visibility}</p> // ok, value is undefined
    </div>
    <div>
      <span>
        {userPosition.main?.temp}  // ok, value is undefined or temp
      </span>
      <span>°C</span>
    </div>
  </>
)}

相关问题