reactjs - 使用 i18next 时如何处理 ESLint react-hooks 'exhaustive-deps' 规则?

标签 reactjs react-hooks react-i18next

我已经添加了 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/

相关文章:

reactjs - react Hook : how to access props within "mount" useEffect & not throw linting warning

javascript - 使用依赖于多个 props 的 useEffect 跟踪一个 props

javascript - react useContext() 性能,自定义钩子(Hook)内的 useContext

reactjs - React i18next Backend-Path 在本地和生产环境中不同

reactjs - GraphQL 突变 : Invariant Violation: Must contain a query definition

node.js - 我需要将用户输入作为获取请求的一部分提交给 unsplash 服务器

javascript - 如何在 ReactJS 中的 Switch 语句中包含组合函数的结果

react-i18next - 检测是否使用了后备语言

reactjs - 使用计数的 i18next 复数返回一个对象而不是字符串

javascript - 如何将信息框的 onclick 事件添加到 ReactJS 中 bingmaps 上的图钉中