如何从react-select multi更新反应状态?

时间:2019-03-08 20:15:05

标签: reactjs filter react-select react-state-management

我正在学习做出反应,并尝试根据所选元素更新反应状态。我正在使用反应选择。现在显示所有数据。但是,当我从选择框中选择选项时,我想更新数据。如果我选择了多个选项,则应该更新过滤所选选项的状态。

const reviews = [
  {
    "id": 1,
    "rating": 5,
    "label": [
      "Sports",
      "Sleep"
    ],
  },
  {
    "id": 3,
    "rating": 5,
    "label": [
      "Sports",
      "Pain"
    ],
  },
];
class SelectCreateFilter extends React.Component {
  state = {
    multi: null,
    data: reviews,
    health: healthBenefitsOptions,
    category: productCategoryOptions, 
    products: productOptions,
  };
  handleChange = name => value => {
    this.setState({
      [name]: value,
      data: this.state.data.filter() //how to perform the data mathcing to reviews.label
    });

  };
  render() {
    return (
      <div>
          <Select
            options={groupedOptions}
            components={components}
            value={multi}
            onChange={this.handleChange('multi')}
            placeholder="Select multiple tags or products for reviews"
            isMulti
            isSearchable
          />
      </div>
    );
  }
}

预先感谢您的帮助。 这是来自codesandbox的代码,因此您可以检查上面的代码 https://codesandbox.io/embed/jlro0vo4n3?fontsize=14

1 个答案:

答案 0 :(得分:2)

根据需要,可以制定不同的过滤策略:

如果要渲染标签中至少包含所选值之一的评论,则可以使用Array.some

  handleChange = name => values => {
    this.setState(state => ({
      [name]: values,
      data:
        values.length > 0  // if at least one value selected
          ? reviews.filter(review => // go through all reviews
              values.some(value => review.label.indexOf(value.label) >= 0) // and see if at least one selected value is in the label of that review
            )
          : reviews // if no value selected, show them all
    }));
  };

如果要渲染必须具有所有选定值的评论,则应使用Array.every

  handleChange = name => values => {
    this.setState(state => ({
      [name]: values,
      data:
        values.length > 0
          ? reviews.filter(review => 
              values.every(value => review.label.indexOf(value.label) >= 0) // check if every selected value is in a row
            )
          : reviews
    }));
  };