gpt4 book ai didi

javascript - 在 ReactJS 中使用搜索框时如何显示来自 API 的信息?

转载 作者:行者123 更新时间:2023-11-29 10:58:56 25 4
gpt4 key购买 nike

我正在使用 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

最佳答案

您可以将 fetch 放在一个单独的函数中,而不是放在 componentDidMount 中,并在组件安装和查询更改时调用它。

如果用户快速键入,您可能会创建多个请求,因此您可以使用 debounce只发送一个请求,或者使用一些东西来验证你总是使用最新请求的结果,比如一个 token

示例

class Search extends Component {
token = null;
state = {
query: "",
people: []
};

onChange = e => {
const { value } = e.target;
this.setState({
query: value
});

this.search(value);
};

search = query => {
const url = `https://swapi.co/api/people?search=${query}`;
const token = {};
this.token = token;

fetch(url)
.then(results => results.json())
.then(data => {
if (this.token === token) {
this.setState({ people: data.results });
}
});
};

componentDidMount() {
this.search("");
}

render() {
return (
<form>
<input
type="text"
className="search-box"
placeholder="Search for..."
onChange={this.onChange}
/>
{this.state.people.map(person => (
<ul key={person.name}>
<li>{person.name}</li>
</ul>
))}
</form>
);
}
}

关于javascript - 在 ReactJS 中使用搜索框时如何显示来自 API 的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com