saga 中的 setTimeout 函数 React.js

setTimeout function in saga React.js

我只想在 5 秒后隐藏 UI 中的撤消按钮。这是我的代码:

Saga.js

function* updateActionListingsSaga({ payload }) {
  try {
    const res = yield call(updateUnpublishedListingsById, payload);
    let unpublishedListings = yield select(UnpublishedListings);
    if (res) {
      const row = unpublishedListings.listingsData.results.find(data => data.id === res.ids[0])
      if (row) {
        row.review_status = payload.review_status
        row.isUndoEnabled = true;
        yield setTimeout(() => {row.isUndoEnabled = false}, 5000)
      }
    }
    
    yield put(updateActionListingSuccess());
  } catch (error) {
    yield put(apiError(error.error || error.message || error));
  }
}

Index.js

item?.isUndoEnabled && (
  <ConfirmDialogBtn
    button={{
      color: 'primary',
      title: 'Undo',
      icon: 'bx bx-undo',
    }}
    msg="Set this Listing as Undo"
    onConfirm={() => handleUpdateListing(item?.id, 'pending')}
  />
)

我正在检索特定行,通过附加 row.isUndoEnabled= true 属性 设置撤消按钮,并在延迟 5 秒后将其设置为 row.isUndoEnabled= false

实际输出:属性 设置为 True 但不隐藏按钮

预期输出:隐藏按钮

希望得到最佳答案。 谢谢

按钮没有隐藏,因为 updateActionListingSuccess 函数在执行超时回调之前被调用。我推荐你:

  1. timeout 函数包装在 Promise 中并等待它完成。
  2. 在承诺解决后立即调用 updateActionListingSuccess
    function* updateActionListingsSaga({ payload }) {
      try {
        const res = yield call(updateUnpublishedListingsById, payload);
        let unpublishedListings = yield select(UnpublishedListings);
        let row = null;
        if (res) {
          row = unpublishedListings.listingsData.results.find(
            data => data.id === res.ids[0]
          );
          if (row) {
            row.review_status = payload.review_status;
            row.isUndoEnabled = true;
          }
        }
        yield put(updateActionListingSuccess());
        if (row) {
          yield new Promise(resolve =>
            setTimeout(() => {
              row.isUndoEnabled = false;
              resolve();
            }, 5000)
          );
        }
        yield put(updateActionListingSuccess()); // update again
      } catch (error) {
        yield put(apiError(error.error || error.message || error));
      }
    }