不变违规,无效钩子调用,useApolloClient

问题描述

我在React Native中遇到此错误:

“不变违反:无效的挂钩调用。只能在函数组件的主体内部调用挂钩。等等”

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

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。如何修复我的代码?

解决方法

那是因为正如React Rules of Hooks中所述,嵌套函数中不能包含钩子,useApollo本身就是一个钩子,因此您必须将其取出来并以不同的方式解决问题

,

好吧,我通过移除外部钩子上的调用来解决此问题:

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()}
  />

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...