如何限制useQuery的api调用只调用一次?

How to restrict api call by useQuery to be called only once?

我有以下组件,它有一个 date 变量。在每次重新渲染时,date 变量都会更新。现在的问题是,当我将日期分配给查询变量时,graphql 一次又一次地无限获取。我调试了代码,发现apollo正在观察date变量,当它接收到一个新值时,它是re.

import React from 'react';
import { getISODate } from '../../dateUtils';
import { useQuery } from '@apollo/react-hooks';
import { GET_EXPENSE_STATUS } from '../../queries';
import get from 'lodash/get';

const ExpenseStatus = (props) => {
  const date = getISODate(); // returns current date as ISO String Format
  const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {
    variables: {
      date
    }
  });
  if (error) return <p>Error :(</p>;
  return(
    <div>
       {get(data, 'expenseStatus.value')}
    </div>
  );
};

我也试过 useLazyQuery。但运气不好。

 const date = getISODate(); // returns current date in ISO String

 const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS, {
     variables: {
       date
     }
 });

 useEffect(() => {
   if(!called) {
     loadExpenseStatus();
   }
 }, []);

所以,有什么办法可以跳过这个观察者吗?我只想接收一次提取调用。

可能有两种解决方案,第一种(初始值 'freezing'):

const [staticDate] = useState( getISODate() );
const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {
  variables: {
    date: staticDate
  }
});

或简单的const [date] = useState( getISODate() );variables: { date } ...当date在其他地方需要当前值时。

第二个(当output/render中不需要'date'值时):

const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS);

useEffect(() => {
  loadExpenseStatus( {
    variables: {
      date: getISODate()
    }
  } );
}, []); // called once

文档:https://www.apollographql.com/docs/react/data/queries/#executing-queries-manually