【发布时间】: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