首页 > 解决方案 > 请求反应挂钩后更新列表

问题描述

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

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

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

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

标签: reactjsasynchronoususe-effectuse-state

解决方案


如果您想确保您正在更新已添加到 的项目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]);


推荐阅读