首页 > 解决方案 > 使用搜索栏组件搜索项目列表

问题描述

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

不过,我遇到了道具进入的时间问题,因为如果在 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);
    }

任何帮助都将不胜感激,认为它归结为对生命周期的理解,但也努力让我的逻辑适合过滤器功能,因此可能也需要帮助!谢谢!

页面外观的视图

标签: arraysreactjssearchfilter

解决方案


看看这个,是同一个思路: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'));

推荐阅读