首页 > 解决方案 > useEffect Hook 中的值不变

问题描述

这是我的组件:

import { useEffect, useState } from "react";

function Com() {
  const [x, setX] = useState(0);
  useEffect(() => {
    //here is some code that I want to run only once.
    //edit: bcz I want to creating variable here and access in setInterval
    setInterval(() => {
      console.log(x);
      //problem is here x not updating
    }, 1000);
  }, []);
  function change() {
    console.log(x);
    // incrementing x on every click
    setX(x + 1);
  }
  return <button onClick={change}>Change X</button>;
}
export default Com;

我想更新 useEffect Hooks 中 x 的值。如果我使用 x 作为依赖数组, useEffect 中的所有代码都会再次运行我不想要的。

标签: reactjsreact-hooks

解决方案


您可以通过将函数传递给setState.

useEffect(() => {
  const interval = setInterval(() => {
    setX(oldX => /* do something about it */)
  }, 1000);

  // don't forget to do clean up
  return () => clearInterval(interval);
}, []);

推荐阅读