簡體   English   中英

useState 未在 React 的 useEffect 中顯示更新的值

[英]useState not showing updated value in useEffect in React

我有一個 useState

const [started, setStarted] = useState(false);

然后我有一個功能,點擊它會將 setStarted 設置為 true

setStarted(true)

然后我有一個useEffect,在那里我有一個調用函數的IntersectionObserver,函數有一個forEach,在那里我正在檢查started,但它總是錯誤的。 我正在做顯示錯誤的控制台日志,並且該功能無法正常工作,所以我確定它是錯誤的。

let options = {
      rootMargin: "0px",
      threshold: [0.5, 0.5]
    };

useEffect(() => {
  let handleStart = (entries) => {
    entries.forEach((entry) => {
      if (started) {
        //do something
      } 
      console.log("started value " + started);
    });
  };
  let observer = new IntersectionObserver(handleStart, options);

  observer.observe(currentRef.current);
}, []);

您需要將started作為useEffect的依賴項。 它應該如下所示:

useEffect(() => {
    if (started) {
      // Do something with started
    }
}, [started])

當你有一個空的依賴數組時, useEffect只會在頁面最初加載(掛載)時運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM