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

Posted

技术标签:

【中文标题】在 ReactJS 中使用搜索框时如何显示来自 API 的信息?【英文标题】:How to show information from API when using search box in ReactJS? 【发布时间】: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

【问题讨论】:

【参考方案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;

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

【讨论】:

以上是关于在 ReactJS 中使用搜索框时如何显示来自 API 的信息?的主要内容,如果未能解决你的问题,请参考以下文章

按下输入文本框时Android键盘不显示

如何使用来自 API 的数据填充选择下拉元素 - ReactJS

ReactJS:如何从输入字段的下拉列表中显示选定的值?

ReactJs中来自API响应的表呈现问题

如何使用 reactJS 和 css 在全屏背景中显示图像?

如何在 Rails 中使用来自 npm 的反应组件