代码之家  ›  专栏  ›  技术社区  ›  David

如何多次使用fetch-get响应?

  •  0
  • David  · 技术社区  · 2 年前

    我想在状态中设置这两个值,以便以后用作变量。

      const [dollarGoal, setDollarGoal] = React.useState(0); 
      const [dollarValue, setDollarValue] = React.useState(0);
      //fetching donation value
      fetch('api', {
          method: 'GET',
        })
        .then(response => response.json())
        .then(r => setDollarValue(r.dollarValue))
        .then(r => setDollarGoal(r.dollarGoal));
    

    但它给出了错误:

    Property 'dollarGoal' does not exist on type 'void'.
    

    如何修复此问题?

    2 回复  |  直到 2 年前
        1
  •  2
  •   Arjun    2 年前

    尝试以下操作:

      fetch('api', {
          method: 'GET',
        })
        .then(response => response.json())
        .then((r) => {
          setDollarValue(r.dollarValue)
          setDollarGoal(r.dollarGoal)
        });
    

    最后两个 .then 需要合并报表。通过调用 。然后 两次,您发送的是 setDollarValue() (一个空函数)到下一个 。然后 ,这不是您想要的。

        2
  •  0
  •   julBayonna    2 年前

    首先,我认为应该将api调用放在useEffect钩子中,因为如果不这样做,那么在使用useState钩子设置响应值之后,将再次触发提取,这可能会导致在它工作时进行无限调用。 那么,我认为您的响应可能不包含名为“dollarValue”的属性。 你试过控制台吗。记录您的响应?