反应多个过滤器下拉菜单

coc*_*coa 4 javascript filter reactjs

我有React app,您可以根据几个不同的属性过滤列表.目前我可以一次过滤每个类别,但我想一次过滤多个类别,因此当您选择更多过滤器时,列表会不断变小.然后,当您清除所有值时,它将返回到原始列表.我怎样才能做到这一点?

演示

我的代码示例

getInitialState: function() {
  return {
    data: this.props.data,
    bender: '',
    nation: '',
    person: '',
    show: ''
  }
},
filterItems: function(val, type) {
   switch (type) {
    case 'bender':
      this.setState({bender: val});
      break;
    case 'nation':
      this.setState({nation: val});
      break;
    case 'person': 
      this.setState({person: val});
      break;
    case 'show':
      this.setState({show: val});
      break;
    default:
      break;
  }
  var filteredItems;
  if (val) {
    filteredItems = this.props.data.filter(function(item) {
      return item[type] === val;
    });
  } else {
    filteredItems = this.props.data;
  }
  this.setState({data: filteredItems});
}
Run Code Online (Sandbox Code Playgroud)

fox*_*nut 11

您的代码一次只能过滤一个条件.您需要遍历四个条件并累积过滤:

["bender", "nation", "person", "show"].forEach(function(filterBy) {
  var filterValue = state[filterBy];
  if (filterValue) {
    filteredItems = filteredItems.filter(function(item) {
      return item[filterBy] === filterValue;
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

完整代码:

http://codepen.io/foxdonut/pen/GpwRJB?editors=001

我希望这对你有所帮助!