javascript - ReactJS 通过多个值搜索输入
问题描述
我在我的页面上有一个搜索和选择过滤器。我遇到的问题是我似乎无法使用多个 json 值进行搜索。
示例值是{ "id": "1", "role": "teacher", "subject": "mathematics", "name": "Jonathan Kovinski" }
,我希望能够使用键和值。
我尝试使用其他一些关于将 json键和值组合到单个数组并将其传递给搜索过滤器的问题,但它没有用。
text = data.filter(info => {
return Object.keys(info).map(function(key) {
var singleOne = JSON.stringify(info[key]);
console.log(info, "This is the json one")
}).toLowerCase().match(searchString);
});
这是我使用所有代码创建的 JS Fiddle 的链接。
我正在尝试将我的搜索栏设置为使用所有键和值来搜索和排序数据。
解决方案
我建议您将filtered
数据放在 state 中的单独键中,以防您想恢复到原始结果,使用Obeject.values
代替并在函数中Object.keys
过滤,data
handleChange
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
data: [],
searchString: "",
filtered: []
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.fetchData();
}
handleChange(e) {
var value = e.target.value;
this.setState({
searchString: value,
filtered: this.state.data.filter(e =>
Object.values(e)
.join(" ")
.toLowerCase()
.match(value)
)
});
}
fetchData() {
fetch("https://api.myjson.com/bins/lo3ls")
.then(response => response.json())
.then(json => {
this.setState({
isLoaded: true,
data: json,
filtered: json
});
})
.catch(error => console.log("parsing failed", error));
}
render() {
var { isLoaded, data } = this.state;
const searchString = this.state.searchString.trim().toLowerCase();
let text = this.state.data;
console.log(text);
if (searchString.length > 0) {
text = text.filter(info => {
return info.role.toLowerCase().match(searchString);
});
}
return (
<div>
<input
type="text"
id="searchbar"
value={this.state.searchString}
onChange={this.handleChange}
placeholder="Search"
name="device"
/>
<select className="category-select" name="categories" onChange={this.handleChange}>
{data.map(info => (
<option value={info.role}>{info.role}</option>
))}
</select>
{/* map through the filtered ones*/}
{this.state.filtered.map(info => (
<div className="display">
<span className="role">Role: {info.role}</span>
<span> Name: {info.name}</span>
<span>, Subject: {info.subject}</span>
</div>
))}
</div>
);
}
}
ReactDOM.render(<Hello name="World" />, document.getElementById("container"));
推荐阅读
- amazon-web-services - 在单个 S3 存储桶中聚合来自不同区域的 KMS 加密日志
- c++ - Linux下重新挂载FS R/W
- c++ - 为什么这个二进制输出代码会导致内存泄漏
- angular - 谷歌分析不会传播点击事件
- laravel-lighthouse - 在 Laravel Lighthouse 中添加自定义类型和解析器
- django - nginx 如何正确设置带有 gunicorn 的 Django 应用程序的公共域名
- node.js - 我如何获得两个不相等的值?在 MongoDB 中
- asp.net-mvc - Vue 从 MVC 控制器中选择下拉菜单
- javascript - 在 Chrome / Mac OS 上检测窗口外的鼠标中键
- sprite-kit - 在 Swift 中向 SKSprite 添加渐变