如何在反应中正确获得axios响应?

时间:2018-08-12 08:55:27

标签: reactjs get response axios

我正在尝试使用axios来获取数据以提供搜索栏功能,但是我无法使其正常运行。当我在下面的searchForPlaces函数中控制台日志响应时,会收到响应,但是当我在应用程序中调用该响应时,却无法定义。

这是我获取数据的函数,位于我的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>
      );
    }
  }

  // ...
}

1 个答案:

答案 0 :(得分:2)

axios请求是异步的,因此您的searchForPlacesResponse将是undefined

您可以改为返回axios请求,并在then中使用querySearchForPlaces等待承诺解决,然后再使用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);
  }

  // ...
}