反应:为什么从useRef更改ref的当前值不会在这里触发useEffect

九次

我有一个问题useRef:如果添加ref.current到的依赖项列表中useEffect,并且更改的值时ref.currentuseEffect不会触发其中的回调

例如:

export default function App() {
  const myRef = useRef(1);
  useEffect(() => {
    console.log("myRef current changed"); // this only gets triggered when the component mounts
  }, [myRef.current]);
  return (
    <div className="App">
      <button
        onClick={() => {
          myRef.current = myRef.current + 1;
          console.log("myRef.current", myRef.current);
        }}
      >
        change ref
      </button>
    </div>
  );
}

是不是应该在useRef.current更改useEffect时运行其中的东西

另外,我知道我可以用useState在这里。这不是我要的。我也知道ref在重新渲染期间保持相同的参考,因此它不会改变。但是我没有做类似的事情

 const myRef = useRef(1);
  useEffect(() => {
    //...
  }, [myRef]);

我将current值放在dep列表中,因此应该进行更改。

杰伊斯444

好的,所以我认为您在这里缺少的是更改引用的值不会导致重新渲染。因此,如果不引起重新渲染,则该函数不会再次运行。这意味着useEffect不再运行。这意味着永远没有机会比较这些值。如果使用状态更改触发重新渲染,您将看到效果将立即运行。所以尝试这样的事情:

export default function App() {
  const [x, setX] = useState();
  const myRef = useRef(1);
  useEffect(() => {
    console.log("myRef current changed"); // this only gets triggered when the component mounts
  }, [myRef.current]);
  return (
    <button
        onClick={() => {
          myRef.current = myRef.current + 1;
          // Update state too, to trigger a re-render
          setX(Math.random());
          console.log("myRef.current", myRef.current);
        }}
      >
        change ref
      </button>
  );
}

现在您可以看到它将触发效果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章