【问题标题】:React redirect after form submit doesn't work correctly表单提交后反应重定向无法正常工作
【发布时间】:2025-11-22 17:05:01
【问题描述】:

我使用 redux 进行状态管理,使用 formik 进行表单。如果提交没有错误,我希望用户重定向到页面,但它不会等待请求完成它只是在提交后立即重定向到页面。

export const editService = (
  serviceId: string,
  body: ServiceCreateType,
  serviceImage: File
) => async dispatch => {
  try {
    dispatch({ type: EDIT_SERVICE });
    const config = await axiosConfig('ownerAccessToken');
    await axios.put(`${API_URL}/services/${serviceId}`, body, config);
    if (serviceImage) {
      await dispatch(uploadServiceImageForOwner(serviceId, serviceImage));
    }
    dispatch({
      type: EDIT_SERVICE_SUCCESS,
      payload: 'Service Edited successfully',
    });
  } catch (error) {
    dispatch({ type: EDIT_SERVICE_FAILED, payload: getErrorMessage(error) });
  }
};

如果serviceError 为空,我希望用户被重定向

onSubmit={async values => {
        await dispatch(
          editService(
            service.serviceId,
            {
              ...values,
              price: machinePrice(price),
              durationMinutes: durationOnMinutes,
              expertUserId: assignedExpertId,
            },
            serviceImage
          )
        );
        if (!isLoading && !servicesError) {
            router.push(
              '/dashboard/expert/[expertname]?view=my-services&type=pending',
              `/dashboard/expert/${userProfile?.expertProfile.name}?view=my-services&type=pending`
            );
        }
      }}

【问题讨论】:

  • 在您的editService 操作中是否返回承诺?也使用editService 函数更新问题
  • 我添加了editService 函数。 @AmilaSenadheera

标签: javascript reactjs typescript redux formik


【解决方案1】:

这样试试

export const editService = (
    serviceId: string,
    body: ServiceCreateType,
    serviceImage: File) =>
    dispatch => {
        return new Promise((resolve, reject) => {
          (async () => {
            try {
                dispatch({ type: EDIT_SERVICE });
                const config = await axiosConfig("ownerAccessToken");
                await axios.put(`${API_URL}/services/${serviceId}`, body, config);
                if (serviceImage) {
                    await dispatch(uploadServiceImageForOwner(serviceId, serviceImage));
                }
                dispatch({
                    type: EDIT_SERVICE_SUCCESS,
                    payload: "Service Edited successfully"
                });
                resolve();
            } catch (error) {
                dispatch({
                    type: EDIT_SERVICE_FAILED,
                    payload: getErrorMessage(error)
                });
                resolve();
            }
          })();
        });
    };

【讨论】:

  • Promise executor functions should not be async.
  • Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'? 它会抛出这些错误
  • 你检查过!isLoading && !servicesError这些放日志吗?
  • 是的,它甚至没有显示,我是否必须从提交功能中删除异步等待