【问题标题】:Navigate to with state updated导航到状态已更新
【发布时间】:2023-01-18 01:55:42
【问题描述】:

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


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 变量没有更新值。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    使用 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 },
          });
        }
      };
    

    【讨论】:

      【解决方案2】:
      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)
      })
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-27
        • 2021-04-21
        • 2020-06-12
        • 2021-02-09
        • 2018-01-24
        • 2016-08-10
        • 2017-10-28
        • 2022-12-31
        • 2021-08-01
        相关资源
        最近更新 更多