我有一个显示的项目列表,并且正在尝试过滤掉某些结果或基于复选框显示它们。搜索功能位于另一个组件中,我正在将项目数组传递给它,还提供了更新父对象状态以使对象发生变化的方法,以及一个重载函数来重置系统。
我对道具的进入时间有疑问,因为如果在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);
}
任何帮助将不胜感激,认为它可以归结为对生命周期的理解,而且还要努力使我的逻辑适合过滤器功能,因此可能也需要帮助! 谢谢!
查看页面外观
答案 0 :(得分:0)
看看这个,它是相同的想法: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'));