我的搜索栏过滤器出现问题。例如,我希望比特币或btc的名字可以在我的平面列表中搜索。然而,它只会在第一个(比特币(上出现,当我键入(btc(时,flatlist不会改变。我注意到,通过切换变量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});
};
这是的问题
let name = item.CoinInfo
? item.CoinInfo.FullName || item.CoinInfo.Name || ''
: '';
name变量成为第一个具有truthy值的项,因此将只比较您首先放置的项(如果两者都不是truthy,则为"(。您需要对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});
};
通过使用或||
运算符,如果第一个值不为真,则将执行第二个值,允许您在需要时搜索FullName
和Name