繁体   English   中英

React 无法在 useEffect() 中使用钩子设置状态

[英]React can't set state with hooks in useEffect()

我对反应还很陌生,并决定开发一个简单的天气应用程序。一旦页面加载,我希望应用程序向用户询问 geoloacaion,然后相应地显示天气数据。

function App() {
  const [weather, setWeather] = useState(null);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(async (position) => {
      let { latitude, longitude } = position.coords;
      const data = await getWeatherByCords(latitude, longitude);
      await setWeather(data); // Line 8
      console.log(weather) //outputs undefined
      setWeather('hhello'); // Line 10
      console.log(weather) //outputs undefined
      let address = await cordsToAddress(latitude, longitude);
    });
  },[]);


  return (
    <div className="App">
      <h3>Weather App</h3>
      <Weather
        data={weather.data}
      />
    </div>
  );
}

export default App;

getWeatherByCords()只是一个辅助函数,它将请求发送到天气 api 并返回其响应

我读到useEffect(() => {},[])钩子等于componentDidMount() ,据我所知应该只在页面加载或刷新时触发,如果我错了,请纠正我

当我尝试设置weather ,将接收到的数据或只是为了测试某个字符串,然后将其传递到<Weather/>组件中,由于某种原因,在这两种情况下都不起作用,当我尝试记录weather在控制台中,我在两种情况下都未定义。

我还应该等待设置天气(如第 8 行)还是不应该(如第 10 行)?

我阅读了钩子并自己弄清楚了。

function App() {
  const [weather, setWeather] = useState({});

  useEffect(() => console.log(weather), [weather]);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(async (position) => {
      let { latitude, longitude } = position.coords;
      const data = await getWeatherByCords(latitude, longitude);
      console.log('setting weather');
      setWeather(data);
      let address = await cordsToAddress(latitude, longitude);
    });
  }, []);


  return (
    <div className="App">
      <h3>Weather App</h3>
      <Weather
        data={weather}
      />
    </div>
  );
}

我之前的代码实际上是设置天气,但它是异步的,所以console.log()没有捕获它。 所以我写了一个钩子,当weather改变时记录weather到控制台( 这个问题对我帮助很大

useEffect(() => console.log(weather), [weather]);

PS我遇到的另一个问题是我的组件正在“刷新”并几乎不断地发送 api 请求,并且因为我只想在页面加载或刷新时发送 api 请求,所以我也将我的navigator代码包装在useEffect()钩子中:

useEffect(() => {
  navigator.geolocation.getCurrentPosition(async (position) => {
    // code related to working with apis
  });
}, []);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM