首页 > 解决方案 > 如何在反应中正确获得axios响应?

问题描述

我正在尝试使用 axios 获取数据以获取搜索栏功能,但我无法让它工作。当我在下面的 searchForPlaces 函数中控制台登录 de 响应时,我得到了响应,但是当我在我的应用程序中调用它时,我得到了未定义。

这是我获取数据的函数,位于我的 utils.js 中:

export function searchForPlaces(dataToSearch) {
  const requestUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/${dataToSearch}.json?access_token=${accessToken}`;

  const result = axios
    .get(requestUrl)
    .then(response => {
      return response;
    })
    .catch(error => {
      return error;
    });
}

这是代码:

class App extends React.Component {
  renderSearchedPlaces() {
    console.log("render");
    return (
      <div>
        {this.state.searchForPlacesResponse.data.features.forEach(place => {
          return <div>{place}</div>;
        })}
      </div>
    );
  }

  querySearchForPlaces() {
    this.searchInputTimeout ? clearTimeout(this.searchInputTimeout) : null;

    console.log(searchForPlaces(this.state.searchInputValue));
    this.searchInputTimeout = setTimeout(
      function() {
        let searchForPlacesResponse = searchForPlaces(
          this.state.searchInputValue
        );

        this.setState({ searchForPlacesResponse });
      }.bind(this),
      400
    );
  }

  renderContent(item) {
    if (item === "share") {
      return (
        <React.Fragment>
          <h2>
            Share with your friends the places that you like(d), or
            dislike(d)...
          </h2>
          <div className="search-nearby">
            <div
              className={
                this.state.searchNearby === "search"
                  ? "search selected"
                  : "search"
              }
              onClick={() => {
                this.state.searchNearby === "search"
                  ? null
                  : this.setState({ searchNearby: "search" });
              }}
            >
              Search
            </div>
            <div
              className={
                this.state.searchNearby === "nearby"
                  ? "nearby selected"
                  : "nearby"
              }
              onClick={() => {
                this.state.searchNearby === "nearby"
                  ? null
                  : this.setState({ searchNearby: "nearby" });
              }}
            >
              Nearby
            </div>
          </div>
          <input
            className="search-input"
            type="text"
            placeholder="Search a place"
            value={this.state.searchInputValue}
            onChange={e => this.setState({ searchInputValue: e.target.value })}
            onKeyUp={() => this.querySearchForPlaces()}
          />
          {this.state.searchForPlacesResponse
            ? this.renderSearchedPlaces()
            : null}
        </React.Fragment>
      );
    }
  }

  // ...
}

标签: reactjsgetresponseaxios

解决方案


axios 请求是异步的,所以你searchForPlacesResponseundefined.

您可以改为返回 axios 请求,并在使用之前使用theninquerySearchForPlaces等待 promise 解决setState

export function searchForPlaces(dataToSearch) {
  const requestUrl = `https://api.mapbox.com/geocoding/v5/mapbox.places/${dataToSearch}.json?access_token=${accessToken}`;

  return axios
    .get(requestUrl)
    .then(response => {
      return response.data;
    })
    .catch(error => {
      console.error(error);
    });
}

class App extends React.Component {
  // ...

  querySearchForPlaces() {
    this.searchInputTimeout ? clearTimeout(this.searchInputTimeout) : null;

    console.log(searchForPlaces(this.state.searchInputValue));
    this.searchInputTimeout = setTimeout(() => {
      searchForPlaces(this.state.searchInputValue)
        .then(searchForPlacesResponse => {
          this.setState({ searchForPlacesResponse });
        });
    }, 400);
  }

  // ...
}

推荐阅读