【问题标题】:invariant violation, invalid hook call, useApolloClient不变违规,无效的钩子调用,使用ApolloClient
【发布时间】:2020-12-01 09:02:57
【问题描述】:

我在 React Native 中遇到了这个错误:

"Invariant Violation: 无效的钩子调用。钩子只能在函数组件的主体内部调用。等等"

我的代码(简化)是这样的:

import { useApolloClient } from '@apollo/react-hooks';
// code

const handleRedirectCalculator = React.useCallback(() => {
    const client = useApolloClient();
    client.clearStore();
    navigation.push('CurrencyConverter');
}, []);

return (
<View>
  <MessageErrorButton
      message='El tiempo de tu cotización a caducado'
      onPress={() => handleRedirectCalculator()}
  />

我想要的是使用 useApollo 挂钩来获取客户端,然后在客户端上使用 clearStore。如何修复我的代码?

【问题讨论】:

  • 我认为你可以在 useCallback 之外定义const client = useApolloClient();

标签: reactjs react-hooks


【解决方案1】:

好的,我通过移除外部钩子的调用来修复:

import { useApolloClient } from '@apollo/react-hooks';
// code

const client = useApolloClient();

const handleRedirectCalculator = React.useCallback(() => {
    client.clearStore();
    navigation.push('CurrencyConverter');
}, []);

return (
<View>
  <MessageErrorButton
      message='El tiempo de tu cotización a caducado'
      onPress={() => handleRedirectCalculator()}
  />

【讨论】:

    【解决方案2】:

    那是因为如 React Rules of Hooks 中所述,嵌套函数中不能有钩子,useApollo 本身就是一个钩子,所以你必须拿出它并以不同的方式解决你的问题

    【讨论】:

    • 谢谢,我就是这么做的
    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 2020-02-16
    • 2019-10-20
    • 1970-01-01
    • 2022-01-24
    • 2020-12-02
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多