【问题标题】:Ensuring React set hook runs synchronously in order确保 React set hook 按顺序同步运行
【发布时间】: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


【解决方案1】:

如何重构您的初始函数以将对象数组作为参数,结构为{key: "", val: ""},然后在函数中迭代该数组,将所有值添加到配对键并仅调用一次setState ,所有新的变化

const updateLicenseInfo = (index, pairs) => {
    const foundLicenseInfo = { ...licenseInfo[index] };
    const licenseInfoItems = [...licenseInfo];
    pairs.forEach((pair)=>{
      foundLicenseInfo[pair.key] = pair.value;
    });
    licenseInfoItems[index] = foundLicenseInfo;
    setLicenseInfo([...licenseInfoItems]);
};

这样称呼

updateLicenseInfo(licenseIndex, [{key:'ID', value:r.ID},
{key:'added', value:true}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    相关资源
    最近更新 更多