我在我的数据列表中有多个过滤器时遇到问题。目前我有一个过滤器工作,如果数据的城市与过滤器城市匹配,它只返回列表项,但我如何同时过滤价格,城市,并一起搜索?
这是我的组件
import React, { Component } from 'react'
import ListingStreamItem from './ListingStreamItem'
import zipcodes from 'zipcodes'
class Home extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {
visitor_city: '',
}
}
componentDidMount() {
const _this = this;
$.get("https://ipinfo.io", function(response) {
console.log(response.city, response.country);
_this.setState({
visitor_city: response.city
})
}, "jsonp");
}
handleChange(e) {
this.setState({
[e.target.name] : e.target.value
})
}
render(){
const user = this.props.user !== null ? true : false
const listings = this.props.listings == null ? 'There are no listings available at this time' : Object.keys(this.props.listings).reverse().map((key) => {
var areEqual = this.state.visitor_city.toUpperCase() === this.props.listings[key].city.toUpperCase();
if (areEqual) {
return (
<li key={key}>
<ListingStreamItem
id={key}
title={this.props.listings[key].title}
desc={this.props.listings[key].description}
price={this.props.listings[key].price}
zipcode={this.props.listings[key].zipcode}
images={this.props.listings[key].listingimages}
/>
</li>
)
}
})
return(
<div>
<select name="visitor_city" onChange={this.handleChange}>
<option value="orlando">Orlando </option>
<option value="new york city">New York City</option>
</select>
<p>Or Zip Code </p>
<input type='number' min="0" name='miles_from_zip' placeholder="miles" value={this.state.miles_from_zip} />
<input type='text' name="zipcode" placeholder="from zip" value={this.state.zipcode} />
<button>Filter </button>
<ul>
{listings}
</ul>
</div>
)
}
}
export default Home
答案 0 :(得分:2)
为什么你不能在你的地图内做另一个(这是一个简单的解决方案,假设你的价格过滤器也处于状态):
const listings = this.props.listings == null ? 'There are no listings available at this time' : Object.keys(this.props.listings).reverse().map(key => {
let {visitor_city, price} = this.state;
let listing = this.props.listings[key];
if (visitor_city.toUpperCase() === listing.city.toUpperCase()
&& (!price || price === listing.price)
) {
return (
...
)
}
})
更清洁的选项可能是查看Array.prototype.filter
功能:
filter()
方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
var longWords = words.filter(word => word.length > 6);
// Filtered array longWords is ["exuberant", "destruction", "present"]
因此,在您的场景中,您可以执行以下操作:
Object.keys(this.props.listings).reverse().filter(key => {
let {visitor_city, price} = this.state;
let listing = this.props.listings[key];
return visitor_city.toUpperCase() === listing.city.toUpperCase()
&& (!price || price === listing.price)
}).map(key => {
...
})