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