等待发货

Waiting for dispatch in thunks

我需要等到 thunks 中的调度完成。之后,我必须将 hook 的状态设置为 true。

这是我的服务:

   export const loadSearchInfoAsync = (product_id: string) => {
      return (dispatch: Dispatch) => {
        SearchService.getSearchInfo(product_id)
          .then((response) => {
            if (response) {

              // Wait until this dispatch is done
              dispatch(searchInfoLoadSuccess(response.data));

            }
          })
          .catch((error) => {
            if (error) {
              dispatch(appErrorState(error.response));
            }
          });
      };
    };

这里是在发送后必须更新的状态

  const handleScan = (data: string | null) => {
    if (!proceed && data) {

      // After this dispatch make setProceed true
      dispatch(loadSearchInfoAsync(data));
      setProceed(true);
    }
  };

我认为在这种情况下,您可能只需将继续代码移动到一个效果中并等待对此的响应?

useEffect(() => {
  if (data.length) { // or do whatever check here to see if it's not empty
    setProceed(true);
  }
}, [data])

也许对你有帮助

const loadSearchInfoAsync = (product_id: string, onSuccess, onFailure) => {
return (dispatch: Dispatch) => {
  SearchService.getSearchInfo(product_id)
    .then((response) => {
      if (response) {

        // Wait until this dispatch is done
        dispatch(searchInfoLoadSuccess(response.data));
        onSuccess()
      }
    })
    .catch((error) => {
      if (error) {
        dispatch(appErrorState(error.response));
        onFailure()
      }
    });
};

};

 const loadSearchInfoPromise = (product_id: string) => {
return new Promise((resolve, reject) => {
  dispatch(loadSearchInfoAsync(product_id, resolve, reject))
}

}

 const handleScan = async (data: string | null) => {
if (!proceed && data) {

  // After this dispatch make setProceed true

  await loadSearchInfoPromise(data).then(() => {
    setProceed(true);
  })
}

};