错误 无法读取未定义的属性(正在读取 'temp') 类型错误:无法读取未定义的属性(正在读取 'temp')

3

这是我的代码(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上使用Optional Chaining运算符,还有一堆控制台日志,但我找不到错。

1个回答

1

您将空值检查放在了错误的对象上。该错误提示您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>
  </>
)}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接