在React中从Axios提取数据的问题

问题描述 投票:0回答:2

我正在创建一个搜索,该搜索将打印出以下API的结果:https://jsonplaceholder.typicode.com/users

在此阶段,我只希望将数据作为搜索结果打印出来。当前,任何搜索之后,显示“无法获取结果。请检查网络”错误消息。

这是我的搜索组件:

import React from "react";
import "../styles.css";
import axios from "axios";

class Search extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      query: "",
      results: {},
      loading: false,
      message: ""
    };

    this.cancel = "";
  }

  fetchSearchResults = (updatedPageNo = "", query) => {
    const pageNumber = updatedPageNo ? `&page=${updatedPageNo}` : "";
    // By default the limit of results is 20
    const searchUrl = `https://jsonplaceholder.typicode.com/users${query}${pageNumber}`;
    if (this.cancel) {
      // Cancel the previous request before making a new request
      this.cancel.cancel();
    }
    // Create a new CancelToken
    this.cancel = axios.CancelToken.source();

    axios
      .get(searchUrl, {
        cancelToken: this.cancel.token
      })
      .then(res => {
        const resultNotFoundMsg = !res.data.length
          ? "There are no more search results. Please try a new search."
          : "";
        this.setState({
          results: res.data,
          message: resultNotFoundMsg,
          loading: false
        });
      })
      .catch(error => {
        if (axios.isCancel(error) || error) {
          this.setState({
            loading: false,
            message: "Failed to fetch results.Please check network"
          });
        }
      });
  };

  handleOnInputChange = event => {
    const query = event.target.value;
    if (!query) {
      this.setState({ query, results: {}, message: "" });
    } else {
      this.setState({ query, loading: true, message: "" }, () => {
        this.fetchSearchResults(1, query);
      });
    }
  };

  renderSearchResults = () => {
    const { results } = this.state;
    if (Object.keys(results).length && results.length) {
      return (
        <ul>
          {results.map(result => (
            <li>{result.name}</li>
          ))}
        </ul>
      );
    }
  };

  render() {
    const { query, message } = this.state;

    return (
      <div className="container">
        {/*Heading*/}
        <h2 className="heading">Live Search: React Application</h2>
        {/*Search Input*/}
        <label className="search-label" htmlFor="search-input">
          <input
            type="text"
            value={query}
            id="search-input"
            placeholder="Search..."
            onChange={this.handleOnInputChange}
          />
          <i className="fa fa-search search-icon" />
        </label>

        {/* Error Message*/}
        {message && <p className="message">{message}</p>}

        {/*Result*/}
        {this.renderSearchResults()}
      </div>
    );
  }
}

export default Search;

我正在创建一个搜索,该搜索将打印以下API的结果:https://jsonplaceholder.typicode.com/users。在此阶段,我只希望将数据作为搜索结果打印出来。当前,...

javascript reactjs search axios
2个回答
0
投票

代码失败的原因在目标searchUrl中。


0
投票

初始化时以及搜索后,需要将this.cancel设置为undefined。像这样的东西:

热门问题
推荐问题
最新问题