所以我试着通过一个搜索框过滤我的星球大战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不是一个函数“。一开始我想既然filter只适用于数组,而我的数据是字符串,我应该使用jedi.split('').filter
。但这似乎不起作用,因为我刚刚得到了"jedi.split不是一个函数”。发生了什么?
发布于 2018-06-10 08:53:11
在运行代码之后,这个链接'https://swapi.co/api/people/1‘返回一个对象(Luke Skywalker)。不能在对象上使用.filter(),它是用于数据数组的。
{name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", …}
当我更改url 'https://swapi.co/api/people/‘并删除1时,我收到一个对象,其中包含results
中的另一个对象数组。
我假设你想搜索一份绝地武士的名单。如果您希望在API中返回列表,则必须在results中更深入地研究此对象。所以你需要按如下方式重构你的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)
我假设在此之后,您将把经过过滤的Jedi列表返回给UI
我在我的搜索字段状态中硬编码了'Luke‘,它成功地返回了1个Jedi
https://stackoverflow.com/questions/50779529
复制相似问题