在 ReactJS 中使用搜索框时如何显示来自 API 的信息?

hel*_*pie 5 javascript api search reactjs

我正在使用 Star Wars API 构建一个 React JS 项目。我的应用程序的目标是能够搜索字符。

这是我的应用程序中搜索组件的代码。

目前,我可以通过 API 检索数据并在页面上显示信息,但我无法弄清楚在搜索时如何显示这些信息。

有任何想法吗?

import React, { Component } from 'react';
class Search extends Component {
  constructor(props){
    super(props)
    this.state = {
      query:'',
      peoples: [],
    }
  }

 onChange (e){
   this.setState({
     query: e.target.value
   })
  if(this.state.query && this.state.query.length > 1) {
     if(this.state.query.length % 2 === 0){
       this.componentDidMount()
     }
   }
 }

componentDidMount(){
  const url = "https://swapi.co/api/people/";
  fetch (url,{
    method:'GET'
  }).then(results => {
    return results.json();
  }).then(data => {
    let peoples = data.results.map((people) => {
      return(
        <ul key={people.name}>
        <li>{people.name}</li>
        </ul>
      )
    })
    this.setState({peoples: peoples});
    console.log("state", peoples)
  })
}

 render() {
   return (
     <form>
       <input
         type="text"
         className="search-box"
         placeholder="Search for..."
         onChange={this.onChange.bind(this)}
       />
       {this.state.peoples}
     </form>
   )
 }
}

export default Search
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 5

您可以将您fetch的函数放在一个单独的函数中,而不是在componentDidMount组件安装和查询更改时调用它。

由于如果用户快速键入,您可能会创建多个请求,因此您可以使用debounce仅发送一个请求,或使用某些内容来验证您始终使用最新请求的结果,例如token.

例子

class Search extends Component {
  token = null;
  state = {
    query: "",
    people: []
  };

  onChange = e => {
    const { value } = e.target;
    this.setState({
      query: value
    });

    this.search(value);
  };

  search = query => {
    const url = `https://swapi.co/api/people?search=${query}`;
    const token = {};
    this.token = token;

    fetch(url)
      .then(results => results.json())
      .then(data => {
        if (this.token === token) {
          this.setState({ people: data.results });
        }
      });
  };

  componentDidMount() {
    this.search("");
  }

  render() {
    return (
      <form>
        <input
          type="text"
          className="search-box"
          placeholder="Search for..."
          onChange={this.onChange}
        />
        {this.state.people.map(person => (
          <ul key={person.name}>
            <li>{person.name}</li>
          </ul>
        ))}
      </form>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)