使用搜索栏组件搜索项目列表



>我有一个正在显示的项目列表,并试图过滤掉某些结果或根据复选框显示它们。搜索函数在另一个组件中,我正在将项目数组传递给它,以及更新父级状态以便对象更改的方法,以及重置系统的重新加载函数。

不过,我对 props 进入的时间有问题,因为如果在 componentDid/WillMount 中设置,子状态数组将返回空。我可以在 onChange 方法中设置状态,但这会导致每次勾选框时重置状态。我应该何时设置子状态,那么每次选中复选框时更新它的最佳方法是什么?

父组件中的子组件调用:

<ManagePostsSearchBar parentResults={filteredPosts} 
results={this.fetchSearchData} filteredPostsUpdated={this.filteredPostsUpdated} 
/> 

子组件句柄更改方法

// 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'));

最新更新