[英]Search Text Filtering only recognizes first input
I am facing an issue with my search bar filter.我的搜索栏过滤器出现问题。 For example, I want names either bitcoin or btc to be searchable in my flatlist.例如,我希望可以在我的平面列表中搜索比特币或 btc 的名称。 However, it only picks up on the first (bitcoin) and when I type (btc) the flatlist is unchanged.但是,它只接收第一个(比特币),当我输入(btc)时,平面列表没有改变。 I have noticed by switching around the variables item.CoinInfo.FullName
or item.CoinInfo.Name
it only picks up whatever is listed first.我注意到通过切换变量item.CoinInfo.FullName
或item.CoinInfo.Name
它只会选择首先列出的任何内容。
search = searchText => {
this.setState({searchText: searchText});
// searchText empty, reset filtered array
if (!searchText) {
this.setState({filteredCryptos: []});
return;
}
let filteredCryptos = this.state.cryptos.filter(function (item) {
// Defaults to empty string
let name = item.CoinInfo
? item.CoinInfo.FullName || item.CoinInfo.Name || ''
: '';
// If no such property, skip
if (!name) {
return false;
}
// Change to both to lowercase, as you want to match 'bitcoin' and 'Bitcoin'
return name.toLowerCase().includes(searchText.toLowerCase());
});
this.setState({filteredCryptos: filteredCryptos});
};
This is the issue这是问题
let name = item.CoinInfo
? item.CoinInfo.FullName || item.CoinInfo.Name || ''
: '';
The name variable becomes the first item that has a truthy value, and thus will only compare whichever item you place first (or '' if both arent truthy). name 变量成为第一个具有真实值的项目,因此只会比较您首先放置的任何项目(或 '' 如果两者都不是真实的)。 You need to do a comparison for both the FullName
and the Name
variable.您需要对FullName
和Name
变量进行比较。
search = searchText => {
this.setState({searchText: searchText});
// searchText empty, reset filtered array
if (!searchText) {
this.setState({filteredCryptos: []});
return;
}
let filteredCryptos = this.state.cryptos.filter(function (item) {
// Defaults to empty string
let {FullName, Name } = item.CoinInfo
// If no such property, skip
if (!Name && !FullName) {
return false;
}
// this way gives Name (short name) precedence
return Name.toLowerCase().includes(searchText.toLowerCase()) ||
FullName.toLowerCase().includes(searchText.toLowerCase());
// this way give FullName precedence
return FullName.toLowerCase().includes(searchText.toLowerCase()) ||
Name.toLowerCase().includes(searchText.toLowerCase())
});
this.setState({filteredCryptos: filteredCryptos});
};
By using the or ||
通过使用或||
operator, if the first value fails to be true, then the second one will be executed, allowing you to search both FullName
and Name
when needed运算符,如果第一个值不为真,则执行第二个,允许您在需要时同时搜索FullName
和Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.