【发布时间】:2021-10-22 17:40:59
【问题描述】:
我有一个反应状态,其中包含一组对象,看起来像这样{ID: 7, LicenseNumber: 'Testing123', LicenseCreator: 7, added: true}
为了操作这个对象的各个值,我准备了一个如下所示的函数:
const updateLicenseInfo = (index, licenseInfoKey, licenseInfoVal) => {
const foundLicenseInfo = { ...licenseInfo[index] };
const licenseInfoItems = [...licenseInfo];
foundLicenseInfo[licenseInfoKey] = licenseInfoVal;
licenseInfoItems[index] = foundLicenseInfo;
setLicenseInfo([...licenseInfoItems]);
};
我的问题是当我连续两次运行这个函数时,我相信钩子的异步特性只会导致最后一个函数运行。
例如,当我调用 API 并尝试更新 ID 时,添加的字段 ID 将为空,但添加的字段已更改。这是那个例子:
postData('/api/licenseInfo/createLicenseInfoAndCreateRelationship', {
LicenseNumber,
RequestLineItemID: procurementLine.ID
})
.then((res) => res.json())
.then((r) => {
updateLicenseInfo(licenseIndex, 'ID', r.ID);
updateLicenseInfo(licenseIndex, 'added', true);
})
如何保证这个函数运行,然后下一个函数同步运行
【问题讨论】:
-
你是对的,两次调用具有 setState 函数调用的函数可能只会导致最后一次调用生效,因为第一次调用尚未完成。老实说,我建议使用第二个函数来处理这个用例。
标签: javascript reactjs asynchronous