gpt4 book ai didi

reactjs - react useEffect 钩子(Hook)和 eslint 警告

转载 作者:行者123 更新时间:2023-12-05 03:34:18 25 4
gpt4 key购买 nike

我正在寻找有关如何解决以下问题的建议:

我有一个组件 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 钩子(Hook)来缓存当前的 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" />

关于reactjs - react useEffect 钩子(Hook)和 eslint 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70189522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com