【问题标题】:How does react useEffect work with useState hook?react useEffect 如何与 useState 挂钩?
【发布时间】:2021-03-19 14:19:22
【问题描述】:

有人可以解释我做错了什么吗? 我有一个反应功能组件,我使用 useEffect 挂钩从服务器获取一些数据并将该数据放入状态值。在获取数据后,我需要在同一 useHook 中使用该状态值,但由于某种原因该值是明确的。看看我的例子,控制台有一个空字符串,但在浏览器上我可以看到那个值。

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.

【问题讨论】:

  • OP 在 dep 数组中没有值

标签: reactjs use-effect


【解决方案1】:

useEffect 钩子将在您的组件呈现后运行,并且只要在第二个参数的数组中传递的依赖项之一发生更改,它将重新运行。

在您的效果中,您正在执行 console.log(value) 但在依赖项数组中您没有将 value 作为依赖项传递。因此,该效果仅在挂载时运行(当 value 仍然是 "" 时),并且再也不会运行。

通过将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;

不确定您需要做什么,但是如果您需要对端点返回的值做某事,您应该使用端点返回的值(而不是状态值)或处理状态值在钩子外面

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;

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2019-05-12
    • 2019-12-31
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多