[英]How to handle ESLint react-hooks 'exhaustive-deps' rule when using i18next?
I have add react-hook/exhaustive-deps and Im having issues deciding how to do things.我添加了 react-hook/exhaustive-deps 并且我在决定如何做事时遇到了问题。
Let's say that I have a function that does an Ajax call to get user data.假设我有一个 function 调用 Ajax 来获取用户数据。 If there is an error then it informs the user about it.
如果有错误,它会通知用户。
const { t } = useTranslation();
useEffect(() => {
async function getUser() {
setLoading(true);
try {
const { user } = await queryUser(userId);
setUser(user);
} catch(error) {
setLoading(false);
if(!error.isAuthenticated) {
t('home');
}
}
}
if (id) {
getUser();
}
}, [t, id])
When the user decides to change the language, Does it mean that it will execute this code again?当用户决定更改语言时,是否意味着它将再次执行这段代码? How can I avoid that?
我怎样才能避免这种情况? I don't want a second Ajax call because the language has changed.
我不想要第二次 Ajax 调用,因为语言已经改变。
I know that I can disable the rule but Im reading everywhere that it is more convenient not to do it.我知道我可以禁用该规则,但我到处都在阅读,不这样做更方便。 Is there any best practices or blog post related to handling common uses cases for react-hook/exhaustive-deps?
是否有与处理 react-hook/exhaustive-deps 的常见用例相关的最佳实践或博客文章?
It seems when you change language new instance of t
is being returned...似乎当您更改语言时,正在返回
t
的新实例......
This is known situation in general, when sometimes you might want only to read some value inside useEffect
but not react to its change, and react team plans to create a hook for it called useEvent
, but officialy it is not available yet.这通常是已知的情况,有时您可能只想读取
useEffect
中的一些值但不对其更改做出反应,并且反应团队计划为其创建一个名为useEvent
的钩子,但官方尚不可用。
Till then, I think closest you could do is something like below.到那时,我认为你能做的最接近的是下面的事情。 Add a new
useEffect
before your main useEffect
.在你的主要
useEffect
之前添加一个新的useEffect
。
let storedT = useRef();
React.useEffect(() => {
storedT.current = t;
});
useEffect(() => {
async function getUser() {
setLoading(true);
try {
const {
user
} = await queryUser(userId);
setUser(user);
} catch (error) {
setLoading(false);
if (!error.isAuthenticated) {
console.log(storedT.current("home"))
}
}
}
if (id) {
getUser();
}
}, [id])
Now, since the storedT
is a ref
, you don't need to add it as a dependency in your second useEffect
, and you can use it there directly.现在,由于
storedT
是一个ref
,你不需要将它作为依赖添加到你的第二个useEffect
中,你可以直接在那里使用它。
But this pattern may have some problems for example if you pass the storedT
to a child component, which calls it inside her own useEffect
, then child components useEffect
might run first, hence storedT
won't be initialized.但是这种模式可能存在一些问题,例如,如果您将
storedT
传递给子组件,该子组件在她自己的useEffect
中调用它,那么子组件useEffect
可能首先运行,因此storedT
不会被初始化。 More info on this pattern and its possible problems.有关此模式及其可能问题的更多信息。
If you don't like above pattern, then maybe as a last resort you could also use:如果您不喜欢上述模式,那么作为最后的手段,您也可以使用:
// eslint-disable-next-line react-hooks/exhaustive-deps
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.