【问题标题】:How to filter api data in React如何在 React 中过滤 api 数据
【发布时间】:2018-06-10 00:04:54
【问题描述】:

所以我试图通过搜索框过滤我的星球大战 api 数据并得到了这个:

class Card extends Component {
  constructor(){
    super()
    this.state = {
      jedi: [],
      searchfield: ''
    }
  }


  // Loop through API
  componentDidMount(){
    fetch('https://swapi.co/api/people/1')
      .then(response => { return response.json()})
      .then(people => this.setState({jedi:people}))
  }

  onSearchChange = (event) => {
    this.setState({searchfield: event.target.value})
    console.log(event.target.value)
  }   

  render() {
    const {jedi, searchfield} = this.state;
    const filteredCharacters = jedi.filter(jedi => {
      return jedi.name.toLowerCase().includes(searchfield.toLowerCase());
    })
  }
}

这是我的 SearchBox 组件

import React from 'react';

const SearchBox = ({searchfield, searchChange})=> {
  return (
    <div className= 'searchbox1'>
      <input className = 'searchbox2' 
        type = 'search' 
        placeholder = 'search character'
        onChange = {searchChange} 
        />
    </div>
  )
}

export {SearchBox};

这是主应用组件中的渲染

render() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={lightsaber} className="App-logo" alt="logo"/>
        <h1 className="App-title">
          Star Wars Character App w/API
        </h1>
      </header>  

      <SearchBox searchChange= {this.onSearchChange} />

      <div className = 'allcards'>
        <Card jedi = {this.filteredCharacters}/>
      </div>
    </div>
  ); 
}

它一直给我错误“jedi.filter 不是函数”。最初我认为由于过滤器仅适用于数组并且我的数据是字符串,所以我会使用 jedi.split('').filter。但这似乎不起作用我刚刚得到“jedi.split 不是函数”。这是怎么回事?

【问题讨论】:

  • 您在 componentDidMount 中进行的 api 调用会生成一个对象,而不是数组或字符串

标签: javascript reactjs api filter


【解决方案1】:

运行代码后,此链接“https://swapi.co/api/people/1”返回单个对象(卢克天行者)。您不能在用于数据数组的对象上使用 .filter()。

{name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", …}

当我更改 url 'https://swapi.co/api/people/' 并删除 1 时,我收到一个对象,其中包含 results 内的另一个对象数组。

我假设您要搜索绝地武士列表。如果您希望在 API 中返回列表,您必须进一步深入研究结果中的该对象。所以你需要重构你的 fetch 如下:

.then(people => this.setState({ jedi:people.results }))

这会返回一个数组中的 10 个对象。

一旦有了这些对象的数组,就可以使用lodash 库进行过滤。 npm i lodash 并要求输入为 import _ from 'lodash'

然后在你解构后的渲染中,你可以运行以下过滤器。

const filtered = _.filter(jedi, (item) => {
   return item.name.indexOf(searchfield) > -1
})

console.log(filtered)

我假设在此之后您会将过滤后的绝地武士列表返回到 UI

我在搜索字段状态中硬编码了“Luke”,它成功返回了 1 个 Jedi

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 2017-07-27
    • 2021-06-07
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多