简体   繁体   English

react useEffect 如何与 useState 挂钩?

[英]How does react useEffect work with useState hook?

Can someone explain what am I'm doing wrong?有人可以解释我做错了什么吗? I have a react functional component, where I use useEffect hook to fetch some data from server and put that data to state value.我有一个反应功能组件,我使用 useEffect 挂钩从服务器获取一些数据并将该数据放入 state 值。 Right after fetching data, at the same useHook I need to use that state value, but the value is clear for some reason.在获取数据之后,我需要同时使用该 state 值,但由于某种原因该值很清楚。 Take a look at my example, console has an empty string, but on the browser I can see that value.看看我的例子,控制台有一个空字符串,但在浏览器上我可以看到那个值。

import "./styles.css";
import React, { useEffect, useState } from "react";

const App = () => {
  const [value, setValue] = useState("");

  function fetchHello() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("Hello World");
      }, 1000);
    });
  }

  const handleSetValue = async () => {
    const hello = await fetchHello();
    setValue(hello);
  };

  useEffect(() => {
    const fetchData = async () => {
      await handleSetValue();
      console.log(value);
    };

    fetchData();
  }, [value]);

  return (
    <div className="App">
      <h1>{value}</h1>
    </div>
  );
};

export default App;

Link to codesandbox . 链接到代码沙盒

The useEffect hook will run after your component renders, and it will be re-run whenever one of the dependencies passed in the second argument's array changes. useEffect挂钩将在您的组件呈现后运行,并且只要在第二个参数的数组中传递的依赖项之一发生更改,它将重新运行。

In your effect, you are doing console.log(value) but in the dependency array you didn't pass value as a dependency.在您的效果中,您正在执行console.log(value)但在依赖项数组中您没有将value作为依赖项传递。 Thus, the effect only runs on mount (when value is still "" ) and never again.因此,效果仅在 mount 上运行(当value仍然是""时)并且再也不会运行。

By adding value to the dependency array, the effect will run on mount but also whenever value changes (which in a normal scenario you usually don't want to do, but that depends)通过向依赖数组添加value ,效果将在挂载时运行,但也会在value更改时运行(在正常情况下,您通常不想这样做,但这取决于)

import "./styles.css";
import React, { useEffect, useState } from "react";

const App = () => {
  const [value, setValue] = useState("");

  function fetchHello() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("Hello World");
      }, 1000);
    });
  }

  const handleSetValue = async () => {
    const hello = await fetchHello();
    setValue(hello);
  };

  useEffect(() => {
    const fetchData = async () => {
      await handleSetValue();
      console.log(value);
    };

    fetchData();
  }, [value]);

  return (
    <div className="App">
      <h1>{value}</h1>
    </div>
  );
};

export default App;

Not sure exactly what you need to do, but if you need to do something with the returned value from your endpoint you should either do it with the endpoint returned value (instead of the one in the state) or handle the state value outside the hook不确定您到底需要做什么,但如果您需要对端点返回的值做某事,您应该使用端点返回值(而不是状态中的值)或处理钩子外的 state 值

import "./styles.css";
import React, { useEffect, useState } from "react";

const App = () => {
  const [value, setValue] = useState("");

  function fetchHello() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve("Hello World");
      }, 1000);
    });
  }

  const handleSetValue = async () => {
    const hello = await fetchHello();

    // handle the returned value here 

    setValue(hello);
  };

  useEffect(() => {
    const fetchData = async () => {
      await handleSetValue();

    };

    fetchData();
  }, []);

  // Or handle the value stored in the state once is set
  if(value) {
    // do something
  }

  return (
    <div className="App">
      <h1>{value}</h1>
    </div>
  );
};

export default App;

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

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