我已经添加了 react-hook/exhaustive-deps,但我在决定如何做事时遇到了问题。
假设我有一个执行 Ajax 调用以获取用户数据的函数。如果有错误,它会通知用户。
const { t } = useTranslation();
const [textErrorKey, setTextErrorKey] = useState();
useEffect(() => {
async function getUser() {
setLoading(true);
try {
const { user } = await queryUser(userId);
setUser(user);
} catch(error) {
setLoading(false);
if(!error.isAuthenticated) {
setTextErrorKey(t('not-authenticated'));
}
}
}
if (id) {
getUser();
}
}, [t, id])
当用户决定改变语言时,是否意味着它会再次执行这段代码?我怎样才能避免这种情况?我不想要第二次 Ajax 调用,因为语言已经改变。
我知道我可以禁用该规则,但我到处都读到不这样做更方便。是否有任何与处理 react-hook/exhaustive-deps 的常见用例相关的最佳实践或博客文章?
最佳答案
我想我可以对每个渲染进行评估而不会受到惩罚:
const [textErrorKey, setTextErrorKey] = useState();
const { t } = useTranslation();
// Takes care of loading data when 'id' changes
useEffect(() => {
async function getUser() {
setLoading(true);
try {
const { user } = await queryUser(userId);
setUser(user);
} catch(e) {
if(!e.isAuthenticated) {
setTextErrorKey('not-authenticated'));
}
} finally {
setLoading(false);
}
}
if (id) {
getUser();
}
}, [id])
return (
<div>
{user?.name ?? t(textErrorKey)}
</div>
)
React 团队制定了解决此类问题的提案:https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md
他们聚在一起有一个名为 useEvent 的新钩子(Hook)。还没有反应。
关于reactjs - 使用 i18next 时如何处理 ESLint react-hooks 'exhaustive-deps' 规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73635418/