Как показать информацию из API при использовании окна поиска в ReactJS? - PullRequest
0 голосов
/ 02 июля 2018

Я использую Star Wars API для создания проекта React JS. Цель моего приложения - уметь искать персонажей.

Вот мой код для поискового компонента в приложении my.

В настоящее время я могу получить данные 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

Ответы [ 2 ]

0 голосов
/ 02 июля 2018

Вы можете поместить 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>
    );
  }
}
0 голосов
/ 02 июля 2018

Вы должны определить это в функции diff, чтобы легко управлять.

import React, { Component } from 'react';

class Search extends Component {

    constructor(props) {
        super(props)
        this.state = {
            query: null,
            peoples: [],
        }
    }


    componentDidMount() {
        this.serachPeople(this.state.query);
    }

    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.serachPeople(this.state.query);
                }
            } else {
                this.serachPeople(this.state.query);
            }
        })
    }

    serachPeople(query) {
        const url = "https://swapi.co/api/people/";

        if (query) {
            // if get value ion query so filter the data based on the query.
            fetch(url, {
                method: 'GET'
            }).then(results => {
                return results.json();
            }).then(data => {
                let peoples = data.results.filter(people => people.name === query).map((people) => {
                    return (
                        <ul key={people.name}>
                            <li>{people.name}</li>
                        </ul>
                    )
                })
                this.setState({ peoples: peoples });
                console.log("state", peoples)
            })
        } else {
            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;

Надеюсь, это поможет вам. Дайте мне знать, если у вас есть запрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...