无效的挂钩调用。当我在 useEffect 中调用 useQuery 时,只能在函数组件主体内部调用 Hooks

Rat*_*rai 8 apollo reactjs react-apollo react-hooks react-apollo-hooks

我在我的 React 项目中使用 apollo-graphql ,并且收到以下错误

无效的挂钩调用。钩子只能在函数组件体内调用

这是我的代码

import React, { useEffect, useState, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";

// **************** COMPONENTS ****************
import { GET_MORTGAGE_JOURNEY } from "../../../../Graphql/Journeys/query";

export default function index() {
  const insuranceId = useSelector((state) => state.mortgage.insuranceId);

  // Panels Heading to show on all panels

  useEffect(() => {
    if (insuranceId) {
      getMortgageData(insuranceId);
    }
  }, [insuranceId]);

  function getMortgageData(insuranceId) {
    const { loading, error, data } = useQuery(GET_MORTGAGE_JOURNEY, {
      variables: { id: insuranceId },
    });
    console.log(data);
  }

  return <section className="mortage-journey"></section>;
}
Run Code Online (Sandbox Code Playgroud)

一旦我运行这个,我就会收到错误,我知道 useQuery 本身是一个钩子,我无法从 useEffect 内部调用它,但是解决方法应该是什么,因为我首先需要来自 redux 状态的 InsuranceId 并将其发送到查询。

谢谢 !

Tus*_*ahi 0

当您从组件顶层以外的任何地方调用它时,您就违反了挂钩规则React

useEffect接受一个回调函数,然后你就可以从中调用你的钩子。这是一个问题。

我发现这个skip选项useQuery可以帮助您有条件地调用useQuery

    const { loading, error, data } = 
    useQuery(GET_MORTGAGE_JOURNEY, {
      variables: { id: insuranceId },
      skip : (!insuranceId)
    });

Run Code Online (Sandbox Code Playgroud)

任何时候insuranceId更改您的回调都会运行,因此它会在挂载后运行一次,然后在后续更改时运行。