首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在React中过滤api数据

如何在React中过滤api数据
EN

Stack Overflow用户
提问于 2018-06-10 08:04:55
回答 1查看 6.9K关注 0票数 0

所以我试着通过一个搜索框过滤我的星球大战api数据,到目前为止得到了这个结果:

代码语言:javascript
运行
复制
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组件

代码语言:javascript
运行
复制
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};

这是主应用程序组件中的渲染

代码语言:javascript
运行
复制
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不是一个函数“。一开始我想既然filter只适用于数组,而我的数据是字符串,我应该使用jedi.split('').filter。但这似乎不起作用,因为我刚刚得到了"jedi.split不是一个函数”。发生了什么?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50779529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档