useLazyQuery onCompleted 函数未被调用

useLazyQuery onCompleted function is not being called

每次使用 useLazyQuery 发送请求时,我都在尝试创建一个基本列表。

这是我的 App 组件。如您所见,我使用了仅限网络的 fetchPolicy,但我仍然遇到了一些问题。首先,我从列表中删除一个项目。删除项目后,我想将相同的值添加到列表中。但是,onCompleted还没有被调用。

另外,当我尝试发送最后一个请求时,onCompleted 没有被再次调用。我尝试了 no-cache fetchPolicy 但我仍然遇到一些问题。它不能正常工作。我做错了什么?

const App = () => {
  const [code, setCode] = useState('');
  const [coins, setCoins] = useState([]);

  const [getData, { loading, data, error }] = useLazyQuery(GET_COIN_PRICE_QUERY, {
    variables: { code },
    fetchPolicy: 'network-only',
    onCompleted: (data) => {
      const hasSameCoin = coins.some((f) => f.id === data.markets[0]?.id);
      if (data.markets.length && !hasSameCoin) {
        setCoins([...coins, data.markets[0]]);
      } else if (data.markets.length <= 0) {
        alert('coin not found');
      }
      if (hasSameCoin) {
        alert('has same value');
      }
    }
  });

  console.log(coins, 'coins');

  return (
    <div>
      <Card setCode={setCode} getData={getData} />
      <CoinList loading={loading} coins={coins} setCoins={setCoins} setCode={setCode} />
    </div>
  );
};

export default App;

这是我的卡片组件。

export const Card = ({ setCode, getData }: Props) => {
  const [inputValue, setInputValue] = useState('');

  const handleChange = (e: any) => {
    setInputValue(e.target.value);
  };

  const onClick = () => {
    if (inputValue) {
      setCode(inputValue);
      setInputValue('');
      getData();
    } else {
      alert('enter a code please');
    }
  };

  return (
    <div className={styles.wrapper}>
      <div>
        <Input placeholder="BTC" value={inputValue} onChange={handleChange} />
      </div>
      <div>
        <Button onClick={onClick}>Add</Button>
      </div>
      <div>
        <div>Use of this service is subject to terms and conditions.</div>
      </div>
    </div>
  )};

这是我的 CoinList 组件。

export const CoinList = ({ loading, coins, setCoins }: Props) => {
  if (loading) {
    return <>Loading...</>;
  }

  const deleteCoin = (id: string) => {
    const filteredCoins = coins.filter((c) => c.id !== id);
    setCoins(filteredCoins);
  };

  return (
    <>
      {coins.map((coin, idx) => {
        return (
          <div className={styles.wrapper} key={`${coin.id}_${idx}`}>
            <div>{coin.baseSymbol}</div>
            <div>{coin.ticker.lastPrice.substring(0, 8)} &euro;</div>

            <div className={styles.delete} onClick={() => deleteCoin(coin.id)}>
              <img src={deleteIcon} alt="deleteIcon" />
            </div>
          </div>
        );
      })}
    </>
  );
};

我在将 notifyOnNetworkStatusChange 添加到 useLazyQuery 的选项中时修复了它。

  const [getData, { loading, data, error }] = useLazyQuery(GET_COIN_PRICE_QUERY, {
    notifyOnNetworkStatusChange: true,
    variables: { code },
    fetchPolicy: 'network-only',
    onCompleted: (data) => {
     ...
    }
  });