UseState 没有在 useEffect 中更新

问题描述 投票:0回答:2

我正在向您寻求帮助以解决我的代码中的问题。我做了很多研究并尝试了不同的方法,但我仍然无法解决这个问题。

我需要 React 代码方面的帮助。具体来说,我想实现当页面加载或刷新时,如果状态为空,应该自动获取城市名称的值(例如伦敦)并向API发出请求。

我为此使用了useEffect,但是使用useState我无法达到预期的效果。由于 useState 在请求执行期间保持为空。我也尝试添加 setTimeout,但它也没有帮助。因此,我不得不寻求帮助,因为无论如何,我想了解问题所在并继续前进。

如果您有任何想法或建议,我将感激不尽。我真的很感激你能给我的任何帮助。

这里是代码的链接:https://gitlab.com/Karwae/weather/-/blob/master/src/App.js

reactjs react-hooks weather-api
2个回答
0
投票

您可以将初始状态设置为“伦敦”

例如: const [location, setLocation] = useState('伦敦');


0
投票

您需要在位置更改时进行

gettingWeather()
更改,因此添加依赖项并使用Callback。

const gettingWeather = React.useCallback( async () => {
    // Same As Before
},[location])

然后让使用效果依赖于gettingWeather函数的变化

useEffect(() => {
  const timer = setTimeout(() => {
    
    gettingWeather();
    console.log(location);
  }, 1000);
  return () => clearTimeout(timer); // Clear the timer on unmount
}, [gettingWeather]);
© www.soinside.com 2019 - 2024. All rights reserved.