reactjs - 请求反应挂钩后更新列表
问题描述
我有一个存储在状态中的项目列表。提交表单后,我将另一个项目添加到列表中,然后将其保存为新状态。这个新添加的项目的状态为“待定”。同时我发送一个发布请求,如果发布请求失败,我想将该特定项目状态更新为“错误”。问题是,请求失败时状态并未更新,因此我试图更新未设置的状态。我正在使用反应钩子,因此一种可能性是仅在状态更新后才调用请求:
useEffect = (()=>{
function getRequest(URL, id, freq) {
request happens here
}
}),[state])
以前,在将 getRequest 函数放入 useEffect 之前,它被子组件中的另一个函数调用。
我的问题由几个部分组成:1)如何将参数 URL、id、freq 获取到 useEffect 函数中?2) 我不想在第一次渲染时运行 getRequest 函数,那么我该如何否定呢?3)我在这里做事的一般模式是好的(我相信它不应该这么困难)。
解决方案
如果您想确保您正在更新已添加到 的项目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]);
推荐阅读
- css - 如何让徽标 img 超出/超出标题
- javascript - 在 Chrome devtools 中查看页面加载时发生的 Android webview 网络请求
- atlassian-sourcetree - 如何一次将多个本地存储库添加到 SourceTree Windows 版本中?
- sql-server - 在 T-SQL 中创建具有参数化名称和表名的视图
- java - Linked List 排序方法在递归过程中给出 StackOverFlow 错误,并比较列表中的元素
- c++ - 我将消息长度声明为什么?整数还是字符?
- powershell - 如何使用 Powershell 正则表达式将 "" 转换为 \"?
- selenium-webdriver - 如何获取 id 的 xpath
- mysql - 当我进行快速数据库导出时,如何找到 phpMyAdmin 运行的 MySQL 命令?
- amazon-web-services - 如果 S3 存储桶的账户所有者将其设为只读,同一账户所有者可以撤消此操作吗?