我是新手,我正在做一个小项目,该项目使用搜索栏来查找我从数据库中获取的数据。
该组件的代码如下:
import React, { Component } from 'react';
class BodyData extends Component {
state = {
query: '',
data: [],
}
handleInputChange = () => {
this.setState({
query: this.search.value
})
this.filterArray();
}
getData = () => {
fetch(`http://localhost:4000/restaurants`)
.then(response => response.json())
.then(responseData => {
// console.log(responseData)
this.setState({
data:responseData
})
})
}
filterArray = () => {
var searchString = this.state.query;
var responseData = this.state.data
if(searchString.length > 0){
// console.log(responseData[i].name);
responseData = responseData.filter(l => {
console.log( l.name.toLowerCase().match(searchString));
})
}
}
componentWillMount() {
this.getData();
}
render() {
return (
<div className="searchForm">
<form>
<input type="text" id="filter" placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange}/>
</form>
<div>
{
this.state.data.map((i) =>
<p>{i.name}</p>
)
}
</div>
</div>
)
}
}
export default BodyData;
所以基本上,我想在输入查询文本时更新状态,并减少我映射的餐厅名称,直到找到匹配项。
据我了解,当我在搜索栏中输入查询时, this.state.data
将被过滤。但是,当我绘制出 this.state.data
时,我得到了整个餐馆列表,而不是我想看到的。
我已经经历了一堆 tutes,我不完全确定如何去做。
任何人都可以帮我解决这个问题吗?也欢迎对代码提出任何其他意见。我是来学习的:)
谢谢!
原文由 jerome 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以保留一个名为
filteredData
data
的所有元素,其中包括您的query
在名称中,然后渲染它。例子