应用多个过滤器反应

汤姆·哈里森

我有2个按钮,当单击它们时,应按novelty或进行过滤,offer以便能够在单击新颖性时对其进行过滤,但是我无法做到这一点,因此,如果同时单击则将按novelty和进行过滤offer

我该如何做,以便在同时点击新颖性和要约时将其全部过滤掉?

https://www.webpackbin.com/bins/-KpVGNEN7ZuKAFODxuER

import React from 'react'

export default class extends React.Component {
  constructor() {
    super()

    this.state = {
      products: [
        { id: 1, novelty: true, offer: false, name: 'test1' },
        { id: 2, novelty: true, offer: true, name: 'test2' },
        { id: 3, novelty: false, offer: true, name: 'test3' } 
        ],
      display: 'all',
      filters: [
        {novelty:'true'},
        {offer: 'true'}
      ]
    }
  }

  setCategory (category) {
    this.setState({
      display: category 
    });
  }

 render() {
   return(
   <div>
      <button onClick={()=>this.setCategory(true)}>Akce</button>
      <button onClick={()=>this.setCategory(true)}>Offer</button>
           {
      this.state.products.filter( product => 
       products.offer === this.state.display ||
        this.state.display==='all')
        .map(product =>
         <div>{product.name}</div>
           )
            }
   </div>
    )
  }
}
西里尔F

这是我想出的最终版本:

import React from 'react'

export default class extends React.Component {
  constructor() {
    super()

    this.state = {
      products: [
        { id: 1, novelty: true, offer: false, name: 'test1' },
        { id: 2, novelty: true, offer: true, name: 'test2' },
        { id: 3, novelty: false, offer: true, name: 'test3' } 
        ],
      filters: {
        novelty: true,
        offer: true
      }
    }
  }

  setCategory (category) {
    this.setState((state) => ({
      filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
    }));
  }

 render() {
   console.log(this.state.filters)
   return(
   <div>
      <button onClick={()=>this.setCategory('novelty')}>Akce</button>
      <button onClick={()=>this.setCategory('offer')}>Offer</button>
           { this.state.products
                       .filter(product => product.novelty === this.state.filters.novelty || product.offer === this.state.filters.offer)
                       .map(product =>
             <div key={product.id}>{product.name}</div>
           )}
   </div>
    )
  }
}

https://www.webpackbin.com/bins/-KpVHqfkjeraq6pGvHij

一些东西:

  • 在您的情况下,使用布尔值而不是字符串会更适合。true而不是'true')。
  • display: 'all'您的用例不需要。您可以根据需要从过滤器计算该值。
  • setCategory接收category要设置为参数的对象。
  • 我将重命名setCategorysetFilter

另外,我正在使用的异步版本setState这使您可以上交功能。

this.setState((state) => ({
      filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
}));

在这里,我Object.assign用来创建一个新的对象。我用他来填充state.filters,最后我更新了想要的过滤器。category将会是novelty或,offer并且感谢我使用的简写版本[category]

最后,我还更新filter功能来检查product.noveltyfilter.noveltyproduct.offerfilter.offer

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章