我有 5 个城市,当您单击一个城市时,它们的天气会显示在一张卡片上,我希望更多详细信息显示在另一张卡片上。我也希望详细卡有第一个城市的初始数据。问题是当我尝试将单击的数据设置为 useEffect 状态时,状态变为空,即使是初始数据。如果我在 useEffect 中添加依赖数组 [props.activeWeather],我可以点击它,它会显示数据,但初始数据不会显示,因为状态显示为空。我正在使用道具向卡片发送点击的城市对象以及第一个数据数组。
const ActiveWeather = (props) => {
const [weather, setWeather] = useState(props.data);
//adding this cause the weather state to go empty?
useEffect(() => {
if (props.activeWeather) {
setWeather(props.activeWeather);
}
}, []);
console.log(weather);
return (
<Container>
<Card>
<Card.Header> {weather?.city}</Card.Header>
{weather?.temp}
</Card>
</Container>
);
};
export default ActiveWeather;
父组件
const fetchCity = async (city) => {
const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}`);
return {
description: res.data.weather[0].description,
icon: res.data.weather[0].icon,
temp: res.data.main.temp,
city: res.data.name,
country: res.data.sys.country,
id: res.data.id,
};
};
function App() {
const [data, setData] = useState([]);
const [activeWeather, setActiveWeather] = useState([]);
useEffect(() => {
const fetchCities = async () => {
const citiesData = await Promise.all(["Ottawa", "Toronto", "Vancouver", "California", "London"].map(fetchCity)).catch((err) => {
console.log("error:", err);
});
setData((prevState) => prevState.concat(citiesData));
};
fetchCities();
}, []);
const handleClick = (event) => {
const weather = JSON.parse(event.target.dataset.value);
setActiveWeather(weather);
};
return (
<div className="App">
<Header />
<Container>
<Row>
<Col>
<WeatherPanel data={data} handleClick={handleClick} />
</Col>
<Col>{data.length > 0 && <ActiveWeather activeWeather={activeWeather} data={data[0]} />}</Col>
</Row>
</Container>
</div>
);
}
export default App;
尝试使用 useEffect 时...
答案 0 :(得分:0)
if (props.activeWeather) {
setWeather(props.activeWeather);
}
总是被执行,因为空数组是真的。所以当 activeWeather
是一个空数组时,weather
被设置为 []
答案 1 :(得分:0)
试试这样:-
useEffect(() => {
if (props.activeWeather) {
setWeather(props.activeWeather);
}}, [props.activeWeather])
在 useEffect 数组中设置您的道具 activeWeather
。如果在您的父组件中所做的任何更改使 useEffect 自动触发。