首页 > 解决方案 > 在 reactjs 中调用

问题描述

这是我的服务方法,我需要通过传递一个 id 对 API 进行 put 调用。这是正确的方法吗,因为我无法访问我的 .put URL

 ENDPOINTS = {
        SAMPLE: "/sample",
      };

这是我的服务方法:

    updateApi(): Promise<any> {
        const config = {
          headers: {
            accept: "application/json",
            "Content-Type": "application/json",
          },
        };

        const data = {
           // data 
        };
 const id = sample.id;
        return http
          .put(`${this.ENDPOINTS.SAMPLE}${id}`, data, config)
          .then((response) => {
            return response.data;
          })
          .catch((error) => {
            throw error;
          });
      }

标签: reactjstypescript

解决方案


不确定你是否有任何理由在http这里使用,但如果你很灵活,那么试试fetchreact 中可用的 API。

      const requestOptions = {
        method: 'PUT',
        headers: {
            accept: "application/json",
            "Content-Type": "application/json",
          },
        body: data
      };

      fetch(`${ENDPOINTS.SAMPLE}/${sample.id}`, requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ // update data here }));

如果您在组件中直接调用 API,则可以将上述代码放在componentDidMount.

如果您遇到任何问题,请告诉我!


推荐阅读