简体   繁体   English

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

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

I'm fairly new to react and decided to develop a simple weather app.Once the page loads I want the app to ask the user for geoloacaion and then display weather data accordingly.我对反应还很陌生,并决定开发一个简单的天气应用程序。一旦页面加载,我希望应用程序向用户询问 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() is just a helper function which sends the request to a weather api and returns its response getWeatherByCords()只是一个辅助函数,它将请求发送到天气 api 并返回其响应

I read that useEffect(() => {},[]) hook is equal to componentDidMount() , and as far as I understand is should trigger only when the page is loaded or refreshed, please correct me if I'm wrong我读到useEffect(() => {},[])钩子等于componentDidMount() ,据我所知应该只在页面加载或刷新时触发,如果我错了,请纠正我

When I try to set weather do the data I received or just for a test to some string,to pass it in the <Weather/> components afterwards, it doesn't work in both cases for some reason and when I try to log weather in console I get undefined in both cases.当我尝试设置weather ,将接收到的数据或只是为了测试某个字符串,然后将其传递到<Weather/>组件中,由于某种原因,在这两种情况下都不起作用,当我尝试记录weather在控制台中,我在两种情况下都未定义。

Also should I await setting weather(as in line 8) or should I not(as in line 10)?我还应该等待设置天气(如第 8 行)还是不应该(如第 10 行)?

I read up on hooks and figured it out by myself.我阅读了钩子并自己弄清楚了。

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>
  );
}

My previous code was actually setting weather, but it was asynchronous so the console.log() didn't capture it.我之前的代码实际上是设置天气,但它是异步的,所以console.log()没有捕获它。 So I wrote a hook that logged weather to console whenever it changed( this question helped me greatly )所以我写了一个钩子,当weather改变时记录weather到控制台( 这个问题对我帮助很大

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

PS Another problem I encountered was that my component was "refreshing" and sending api requests almost constantly, and as I wanted to send an api request only on page load or refresh I wrapped my navigator code also in useEffect() hook: 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.

相关问题 无法使用钩子在 React 中设置状态 - Can't set state in React using hooks 无法对未安装的组件执行 React state 更新(useEffect 反应挂钩) - Can't perform a React state update on an unmounted component (useEffect react hooks) React Hooks:在 useEffect 中使用 useState 不会在第一次渲染后立即设置状态 - React Hooks: using useState inside useEffect doesn't set the state immediately after first rendering React Hooks useEffect 不会使用正确的状态 - React Hooks useEffect won't use the correct state React Hooks:无法在 useEffect() return 中更改父级的任何内容 - React Hooks: Can't change anything from parent in useEffect() return 反应自定义钩子状态改变但使用效果不重新渲染 - React custom hooks state change but useeffect not rerendering React - 使用反应钩子,在 useEffect 中设置一个数组 state 并观察它导致无限循环? - React - Use react hooks, set an array state in useEffect and watch it cause Infinite loop? React hooks:当 state 本身是依赖项时,如何在 useEffect 中更新 state ? - React hooks : how can I update a state within useEffect when the state itself is the dependency? React Hooks:如何正确设置 useEffect 以处理对表单中字段的 state 的更改? - React Hooks: How do I properly set up useEffect to handle changes to the state of a field in a form? 如何在 React 的 useEffect 中设置状态? - How to set the state in useEffect in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM