[英]Proper way to add useEffect in react to call once to satisfy eslint react-hooks/exhaustive-deps?
I'm using eslint react-hooks/exhaustive-deps the problem I'm having is my component needs to call only once regardless of changes on props.我正在使用 eslint react-hooks/exhaustive-deps我遇到的问题是我的组件只需要调用一次,而不管道具的变化。 It is fine with
[]
but when using dependencies it is called multiple time. []
很好,但是当使用依赖项时,它会被多次调用。
my code is (with some omitted)我的代码是(省略了一些)
// some logic for tracking change in realtime
<Component trackingCode=tracking />
export default function Component(props){
// if I use depedencies, it will called multiple times because
// trackingCode keep changing
React.useEffect(()=>{
// some code
// fetch function
const _updateSession = async () => {
const tracking = props.trackingObject;
const formData = new URLSearchParams();
formData.append('trackingCode', tracking.trackingCode);
formData.append('sessionCode', tracking.sessionCode);
formData.append('content', trackingStage);
try {
const req = await fetch(`https://example.com/tracking/${tracking.id}/`, {
method: 'PUT',
body: formData,
})
const res = await req.json();
switch (req.status) {
case 200:
props.setQuestion('trackingObject', res);
break
}
} catch (err) {
console.log(err)
}
}
_updateSession()
},[props.trackingCode])
// if props.trackingCode is ommited like so [] it works just fine
return (
<>
// some code
</>)
}
I tried to use useRef
but somehow the trackingcode is empty.我尝试使用
useRef
但不知何故跟踪代码为空。 Is there a way to satisfy the dependencies without making it call multiple times?有没有办法在不多次调用的情况下满足依赖关系?
thanks谢谢
Proper way is that if you want to execute the useEffect at once just don't pass the dependencies in in dependency array.正确的方法是,如果你想立即执行 useEffect 只是不要在依赖数组中传递依赖项。 I know you mentioned it but its right way.
我知道你提到了它,但它是正确的方式。 If you want to run useEffect on state change then pass the state variable in dependency array.
如果要在 state 更改上运行 useEffect,则在依赖数组中传递 state 变量。
React.useEffect(()=>{
// some code
// fetch function
const _updateSession = async () => {
const tracking = props.trackingObject;
const formData = new URLSearchParams();
formData.append('trackingCode', tracking.trackingCode);
formData.append('sessionCode', tracking.sessionCode);
formData.append('content', trackingStage);
try {
const req = await fetch(`https://example.com/tracking/${tracking.id}/`, {
method: 'PUT',
body: formData,
})
const res = await req.json();
switch (req.status) {
case 200:
props.setQuestion('trackingObject', res);
break
}
} catch (err) {
console.log(err)
}
}
_updateSession()
},[])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.