所以我试着通过一个搜索框过滤我的星球大战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不是一个函数”。发生了什么?
https://stackoverflow.com/questions/50779529
复制相似问题