【问题标题】:Update list after request react hooks请求反应挂钩后更新列表
【发布时间】:2020-04-09 18:35:46
【问题描述】:

我有一个存储在状态中的项目列表。提交表单后,我将另一个项目添加到列表中,然后将其保存为新状态。这个新添加的项目的状态为“待定”。同时我发送一个发布请求,如果发布请求失败,我想将该特定项目状态更新为“错误”。问题是,请求失败时状态并未更新,因此我试图更新未设置的状态。 我正在使用反应钩子,所以一种可能性是仅在状态更新后调用请求:

useEffect = (()=>{
    function getRequest(URL, id, freq) {
       request happens here
    }
}),[state])

以前,在将 getRequest 函数放入 useEffect 之前,它被子组件中的另一个函数调用。

我的问题包括几个部分: 1) 如何将参数 URL、id、freq 获取到 useEffect 函数中? 2) 我不想在第一次渲染时运行 getRequest 函数,那么我该如何否定呢? 3)我在这里做事的一般模式是好的(我相信它不应该这么困难)。

【问题讨论】:

  • 这不是您使用useState 函数的方式。你的意思是useEffect
  • 是的,谢谢,刚刚编辑

标签: reactjs asynchronous use-effect use-state


【解决方案1】:

如果您想确保更新已添加到 state 的项目,那么同步进行此操作的方法是使用 useEffect

但是,我添加了一个额外的state 变量,它表示项目的数量。
然后,每当添加新项目时,都会执行 API 请求并相应地更新(现有)项目:

const [itemsAmount, setItemsAmount] = setState(0);
const [items, setItems] = setState([]);

function addItem(itemData) {
  const newItem = {
    ...itemData,
    status: 'pending',
  }
  setItems([...items, newItem]);
  setItemsAmount(itemsAmount + 1);
};

useEffect(async () => {
  try {
    // Execute the API call
    const response = await apiCall();
    if (resposne && response.data) {
      // Add the successfully updated version of the item
      newItem.status = 'done';
      newItems.data = response.data;
      setItems([...items, newItem]);
    }
  } catch (err) {
    // If the API call fails, add the "failed" version of the item
    newItem.status = 'failed';
    setItems([...items, newItem]);
  }
}, [itemsAmount]);

【讨论】:

  • 这是我做事的顺序,问题是我无法更新该项目的状态,因为它没有设置。
  • @mdc29 刚刚意识到你在问什么,并相应地更新了我的答案。造成误会请见谅
猜你喜欢
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2010-10-31
  • 2021-05-13
相关资源
最近更新 更多