关于reactjs:在use内更改多个状态效果导致react-hooks / exhaustive-deps警告

Mutate multiple states from within useEffect causes react-hooks/exhaustive-deps warning

我正在玩React Hooks。单击按钮后,我要增加一个计数器。计数器增加后,应用程序不应允许进一步增加,直到将clicked重置为false为止。

我想到了这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function App() {
  const [counter, setCounter] = useState(0);
  const [clicked, setClicked] = useState(false);

  useEffect(() => {
    if (clicked) {
      setCounter(counter + 1);
      setTimeout(() => {
        setClicked(false);
      }, 2000);
    }
  }, [clicked]);

  return (
   
      <p>Clicked: {String(clicked)}</p>
      <p>Counter: {counter}</p>
      <button type="button" onClick={() => setClicked(true)}>
        Click me
      </button>
   
  );
}

它实际上有效。但是React正在抱怨以下警告:

React Hook useEffect has a missing dependency: 'counter'. Either
include it or remove the dependency array. You can also do a
functional update 'setCounter(c => ...)' if you only need 'counter' in
the 'setCounter' call. (react-hooks/exhaustive-deps)

当我将计数器添加到依赖项时,useEffect将进入无限循环,因为clicked为true,并且在useEffect中调用了setCounter。

我希望计数器仅在单击时从false更改为true时才增加。如果依赖项列表仅包含被单击的内容,则可以使用,但是React对此表示抱怨。

亲自尝试一下:https://codesandbox.io/s/dreamy-shadow-7xesm


尝试使用以下方法替换setCounter(counter 1):

1
setCounter(counter => counter + 1)

就像警告说的那样。应该解决它。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React, { useState, useEffect } from"react";
import ReactDOM from"react-dom";

import"./styles.css";

function App() {
  const [counter, setCounter] = useState(0);
  const [clicked, setClicked] = useState(false);

  useEffect(() => {
    if (clicked) {
      setClicked(false);
      setCounter(counter + 1);
    }
  }, [clicked, counter]);

  return (
   
      <p>Clicked: {String(clicked)}</p>
      <p>Counter: {counter}</p>
      <button type="button" onClick={() => setClicked(true)}>
        Click me
      </button>
   
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

如果您删除超时(顺便说一句,这是什么意思?),那么您遇到的无限循环问题将不复存在,您是否打算实施去抖或抑制功能?我可以编辑此答案以实现您想要的