簡體   English   中英

反應 useEffect 鈎子和 eslint 警告

[英]React useEffect hook and eslint warning

我正在尋找有關如何解決以下問題的建議:

我有一個組件 A,它有兩個狀態,state1 和 state2。

如果我只想在 state1 更改時運行效果,但在 useEFfect 回調中我使用 state2 的值,我該如何解決有關數組依賴 eslint react hooks 警告的問題?

前任。

function A() {
    const [state1, setState1] = useState(0);
    const [state2, setState2] = useState(0);

    useEffect(() => {
        const a = state1 + state2;
        // do some async logic using a
 
    }, [state1]); //Here eslint react hooks rule requests adding state2 to the dependency array!

return <div> some text </div>

}

常見的方法通常是禁用專門針對該行的 linting 規則。

function A() {
  const [state1, setState1] = useState(0);
  const [state2, setState2] = useState(0);

  useEffect(() => {
    // do some async logic using a
    const a = state1 + state2;

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state1]);

  return <div> some text </div>;
}

但這里的缺點是,如果依賴項實際發生變化並且您忘記更新依賴項數組,它可能會掩蓋依賴項問題。

您可以使用 React ref 和附加的useEffect掛鈎來緩存當前state2值,並在另一個useEffect回調中引用它。

function A() {
  const [state1, setState1] = useState(0);
  const [state2, setState2] = useState(0);

  const state2Ref = useRef(state2);

  useEffect(() => {
    state2Ref.current = state2;
  }, [state2]);

  useEffect(() => {
    // do some async logic using a
    const a = state1 + state2Ref.current;
  }, [state1]);

  return (
    ...
  );
}

 function A() { const [state1, setState1] = React.useState(0); const [state2, setState2] = React.useState(0); const state2Ref = React.useRef(state2); React.useEffect(() => { state2Ref.current = state2; }, [state2]); React.useEffect(() => { // do some async logic using a const a = state1 + state2Ref.current; console.log("effect called", a); }, [state1]); return ( <div> some text <div> <button type="button" onClick={() => setState1((c) => c + 1)}> Update State 1 </button> <button type="button" onClick={() => setState2((c) => c + 1)}> Update State 2 </button> </div> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render( <A />, rootElement );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="root" />

您需要將// eslint-disable-next-line react-hooks/exhaustive-deps添加到您的 userEffect 中,如下所示:

function A() {
    const [state1, setState1] = useState(0);
    const [state2, setState2] = useState(0);

    useEffect(() => {
        const a = state1 + state2;
        // do some async logic using a


       // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [state1]); //Here eslint react hooks rule requests adding state2 to the dependency array!

    return <div> some text </div>

}

暫無
暫無

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

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