【发布时间】:2018-12-10 14:04:44
【问题描述】:
我正在使用 Star Wars API 构建一个 React JS 项目。我的应用程序的目的是能够搜索字符。
这是我的应用中搜索组件的代码。
目前我可以通过 API 检索数据并在页面上显示信息,但我不知道在搜索时如何显示这些信息。
有什么想法吗?
import React, { Component } from 'react';
class Search extends Component {
constructor(props){
super(props)
this.state = {
query:'',
peoples: [],
}
}
onChange (e){
this.setState({
query: e.target.value
})
if(this.state.query && this.state.query.length > 1) {
if(this.state.query.length % 2 === 0){
this.componentDidMount()
}
}
}
componentDidMount(){
const url = "https://swapi.co/api/people/";
fetch (url,{
method:'GET'
}).then(results => {
return results.json();
}).then(data => {
let peoples = data.results.map((people) => {
return(
<ul key={people.name}>
<li>{people.name}</li>
</ul>
)
})
this.setState({peoples: peoples});
console.log("state", peoples)
})
}
render() {
return (
<form>
<input
type="text"
className="search-box"
placeholder="Search for..."
onChange={this.onChange.bind(this)}
/>
{this.state.peoples}
</form>
)
}
}
export default Search
【问题讨论】:
标签: javascript reactjs api search