4

我正在尝试构建一个可用于表上任何 CRUD 操作的表单。对于更新操作,我想将变量与路由一起传递。所有这些都工作正常,但是当我使用惰性查询调用查询时,它对前几次调用什么都不做,然后在第三次调用时返回数据。这正常吗?我是否调用了错误的查询?有没有办法等待查询返回数据?

import React, { useState, useEffect } from "react";
import Router, { useRouter } from "next/router";

import Container from "react-bootstrap/Container";

import { useLazyQuery } from "@apollo/react-hooks";
import { GET_PLATFORM } from "../graphql/platforms";

export default function platformsForm(props) {
  const router = useRouter();

  // grab the action requested by caller and the item to be updated (if applicable)
  const [formAction, setFormAction] = useState(router.query.action);
  const [formUpdateId, setFormUpdateId] = useState(router.query.id);

  const [
    getPlatformQuery,
    { loading, error, data: dataGet, refetch, called }
  ] = useLazyQuery(GET_PLATFORM, {
    variables: { id: formUpdateId }
  });

  useEffect(() => {
    console.log("update");
    // var dataReturned = getPlatformLookup(formUpdateId);

    !called && getPlatformQuery({ variables: { id: formUpdateId } });
    if (dataGet && dataGet.Platform.platformName) {
      console.log(
        dataGet.Platform.platformName,
        dataGet.Platform.platformCategory
      );
    }
  }),
    [];

  return (
    <Container>
      <h4>
        Name: {dataGet && dataGet.Platform.platformName}
        <br />
        Cat: {dataGet && dataGet.Platform.platformCategory}
        <br />
        formAction: {formAction}
        <br />
        formUpdateId: {formUpdateId}
        <br />
      </h4>
    </Container>
  );
}
4

1 回答 1

2

要调用 useLazyQuery,您需要使用useEffect并传递空数组[],这样您就可以准确地调用一次查询,这在您的代码中已经完成(您的 useEffect 中存在语法错误,)缺失)。此外,您不能dataGet在 useEffect 回调中使用从lazyQuery 返回的数据()。

你应该这样做:

// this useEffect hook will call your lazy query exactly once
useEffect(() => {
    getPlatformQuery({ variables: { id: formUpdateId } });

  }, []);

// you can fetch your data here (outside of the useEffect Hook)
if (dataGet && dataGet.Platform.platformName) {
      console.log(
        dataGet.Platform.platformName,
        dataGet.Platform.platformCategory
      );
 }
return(<Container>
      <h4>
        Name: {dataGet && dataGet.Platform.platformName}
        <br />
        Cat: {dataGet && dataGet.Platform.platformCategory}
        <br />
        formAction: {formAction}
        <br />
        formUpdateId: {formUpdateId}
        <br />
      </h4>
    </Container>);

于 2020-03-31T10:00:41.507 回答