簡體   English   中英

react useEffect 如何與 useState 掛鈎?

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

有人可以解釋我做錯了什么嗎? 我有一個反應功能組件,我使用 useEffect 掛鈎從服務器獲取一些數據並將該數據放入 state 值。 在獲取數據之后,我需要同時使用該 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();
    setValue(hello);
  };

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

    fetchData();
  }, [value]);

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

export default App;

鏈接到代碼沙盒

useEffect掛鈎將在您的組件呈現后運行,並且只要在第二個參數的數組中傳遞的依賴項之一發生更改,它將重新運行。

在您的效果中,您正在執行console.log(value)但在依賴項數組中您沒有將value作為依賴項傳遞。 因此,效果僅在 mount 上運行(當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;

不確定您到底需要做什么,但如果您需要對端點返回的值做某事,您應該使用端點返回值(而不是狀態中的值)或處理鈎子外的 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