我有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>
)
}
}
答案 0 :(得分:9)
这是我提出的最终版本:
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
。setCategory
重命名为setFilter
另外,我正在使用setState
的asycnhronous版本。这允许您提交功能。
this.setState((state) => ({
filters: Object.assign({}, state.filters, { [category]: !state.filters[category] })
}));
这里我使用Object.assign
创建一个新对象。我用state.filters
填充他,最后我更新了你想要的过滤器。
category
将novelty
或offer
,并且由于我使用的是[category]
的速记版本。
总而言之,我还会更新您的filter
功能,以product.novelty
对filter.novelty
或product.offer
filter.offer