【问题标题】:How to show information from API when using search box in ReactJS?在 ReactJS 中使用搜索框时如何显示来自 API 的信息?
【发布时间】:2018-12-10 14:04:44
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: javascript reactjs api search


    【解决方案1】:

    您可以将 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>
        );
      }
    }
    

    【讨论】:

    • 为什么不用setTimeout() 来实现这个搜索功能?
    【解决方案2】:

    您必须在 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;
    

    我希望这对你有帮助。如果您有任何疑问,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多