reactjs 导航到,状态已更新

mm5n2pyu  于 2023-02-12  发布在  React
关注(0)|答案(2)|浏览(157)

我有一个确认按钮,它实现了一个请求并重定向到另一个组件。我如何在导航到新组件之前等待数据?

const {
    isLoading,
    error,
    request
} = useHttp();

const confirmHandler = () => {
      request({
        url: API_PATH.create_coupledCertificates,
        method: "POST",
        contentType: "application/json",
        body: body,
      });
    }
    navigate(component, {
      state: { isLoading, error },
    });
  };

问题是,这样一来,isLoading和error变量就没有更新的值。

qxsslcnc

qxsslcnc1#

使用async/await语法:

const confirmHandler = async () => {
    await request({
        url: API_PATH.create_coupledCertificates,
        method: "POST",
        contentType: "application/json",
        body: body,
    });
    navigate(component, {
      state: { isLoading, error },
    });
  };

Promise

const confirmHandler = () => {
    return request({
        url: API_PATH.create_coupledCertificates,
        method: "POST",
        contentType: "application/json",
        body: body,
    })
    .then(() => {
      navigate(component, {
        state: { isLoading, error },
      });
    }
  };
piok6c0g

piok6c0g2#

const confirmHandler = () => {
  request({
    url: API_PATH.create_coupledCertificates,
    method: "POST",
    contentType: "application/json",
    body: body,
  })
    .then((response) => {
      // do wharever you want here you can use response
      navigate(component, {
        state: { isLoading, error },
      });
    })
    .catch((error) => {
      console.log(error);
    });
};

相关问题