arrays - 使用搜索栏组件搜索项目列表
问题描述
我有一个显示项目列表,并试图过滤掉某些结果或根据复选框显示它们。搜索功能在另一个组件中,我将项目数组传递给它,以及更新父级状态以使对象更改的方法,以及用于重置系统的重新加载功能。
不过,我遇到了道具进入的时间问题,因为如果在 componentDid/WillMount 中设置子状态数组返回空。我可以在 onChange 方法中设置状态,但这会导致每次选中一个框时都会重置状态。我什么时候应该设置子状态,那么每次勾选一个框时更新它的最佳方法是什么?
父组件中的子组件调用:
<ManagePostsSearchBar parentResults={filteredPosts}
results={this.fetchSearchData} filteredPostsUpdated={this.filteredPostsUpdated}
/>
子组件handleChange方法
// Checkboxes should change what is displayed each tick, by filtering the array
handleCheckBox=(e)=>{
this.setState ({
[e.target.id]: e.target.value
});
if (!e.target.checked) {
this.setState({[e.target.id]: ''
});
// Not sure where this goes, as it won't update quickly enough in componentDid/WillMount,
// only seems to work here
this.setState({
parentResults: this.props.parentResults
});
// trying to create a new array with search results
var filterArray = this.state.parentResults.filter(
result => result.viewable===this.state.hidden
)
}
console.log(this.state);
}
任何帮助都将不胜感激,认为它归结为对生命周期的理解,但也努力让我的逻辑适合过滤器功能,因此可能也需要帮助!谢谢!
页面外观的视图
解决方案
看看这个,是同一个思路:https ://codepen.io/mtclmn/pen/QyPVJp
var FilteredList = React.createClass({
filterList: function(event){
var updatedList = this.state.initialItems;
updatedList = updatedList.filter(function(item){
return item.toLowerCase().search(
event.target.value.toLowerCase()) !== -1;
});
this.setState({items: updatedList});
},
getInitialState: function(){
return {
initialItems: [
"Apples",
"Broccoli",
"Chicken",
"Duck",
"Eggs",
"Fish",
"Granola",
"Hash Browns"
],
items: []
}
},
componentWillMount: function(){
this.setState({items: this.state.initialItems})
},
render: function(){
return (
<div className="filter-list">
<form>
<fieldset className="form-group">
<input type="text" className="form-control form-control-lg" placeholder="Search" onChange={this.filterList}/>
</fieldset>
</form>
<List items={this.state.items}/>
</div>
);
}
});
var List = React.createClass({
render: function(){
return (
<ul className="list-group">
{
this.props.items.map(function(item) {
return <li className="list-group-item" data-category={item} key={item}>{item}</li>
})
}
</ul>
)
}
});
React.render(<FilteredList/>, document.getElementById('app'));
推荐阅读
- java - 如何执行 OpenJDK 调试包
- html - 移动 Safari 浏览器的问题
- c# - “没有给出与所需形式参数相对应的参数” - 尝试测试 OOP 继承时
- tensorflow - 在带有 TF2 后端的 Keras 中实现的 LSTM 的损失保持不变,并且在大型数据集上训练时基本不会学习参数
- android - 在 NavDrawer 中按下项目时执行代码
- javascript - Create-react-app 没有在 iOS 上加载 JavaScript?
- python - git private repo 上的碰撞版本,现在安装要求失败
- python - 当我单击按钮时,它不会将数据写入变量
- sql - 特定部分的 SQL 运行总计
- mongodb - 连接MongoDB atlas集群与morphia