【发布时间】:2017-08-14 02:42:03
【问题描述】:
我正在尝试根据搜索栏文本搜索平面列表。我遇到的问题是,当用户输入错误......说他们想输入“burger”但错误地输入了“burget”时,它不会返回任何内容。当用户删除“t”时,它应该使用与“burge”部分匹配的最后一个文本再次重新呈现平面列表。
注意:使用 react-native-elements 搜索栏,它允许我只用 e 或 event 调用文本。
到目前为止我在 Main.js 文件中的内容:
searchText = (e) => {
let text = e.toLowerCase();
let trucks = this.state.data;
// search by food truck name
let filteredName = trucks.filter((truck) => {
return truck.name.toLowerCase().match(text);
});
// if no match and text is empty
if(!text || text === '') {
console.log('change state');
this.setState({
data: initial
});
}
// if no name matches to text output
else if(!Array.isArray(filteredName) && !filteredName.length) {
console.log("not name");
this.setState({
data: [],
});
}
// if name matches then display
else if(Array.isArray(filteredName)) {
console.log('Name');
this.setState({
data: filteredName,
});
}
};
<View style={styles.container}>
<SearchBar
round
lightTheme
containerStyle={styles.search}
ref="search"
textInputRef="searchText"
onChangeText={this.searchText.bind(this)}
placeholder='Search by Truck Name...'
/>
<TruckList getTruck={(truck) => this.setTruck(truck)} truckScreen={this.truckScreen} data={this.state.data}/>
</View>
然后是 TruckList.JS:
export default class TruckList extends Component {
// rendering truck screen
renderTruckScreen = (item) => {
this.props.truckScreen();
this.props.getTruck(item);
}
render() {
return(
<List style={styles.list}>
<FlatList
data={this.props.data}
renderItem={({ item }) => (
<ListItem
roundAvatar
avatar={{uri: item.pic1}}
avatarStyle={styles.avatar}
title={item.name}
titleStyle={styles.title}
subtitle={
<View style={styles.subtitleView}>
<Text style={styles.subtitleFood}>{item.food}</Text>
<View style={styles.subtitleInfo}>
<Icon
name="favorite"
size={20}
color={"#f44336"}
style={styles.subtitleFavorite}
/>
<Text style={styles.subtitleFavoriteText}>{item.favorited} favorited</Text>
</View>
</View>
}
onPress={() => this.renderTruckScreen(item)}
/>
)}
keyExtractor={(item) => item.uid}
ListFooterComponent={this.footer}
/>
</List>
)
}
}
我尝试了其他几种方法都无济于事。此外,我见过的为 React Native 工作的唯一解决方案是使用 ListView,它会及时贬值。所以我试图用新的 FlatList 组件来做到这一点。
感谢您的帮助!
【问题讨论】:
-
有什么问题?用户修改搜索文本时是否不会重新渲染?
-
@Umesh 问题在于,当用户输入错误时,数据被设置为
[],然后当他们删除错误输入时,数据应重置回搜索的最后状态......只是还没有弄清楚它是如何工作的。可能设置以前的状态然后以某种方式调用它? -
当用户输入错误时,你的结果是空的 [ ] 但是当用户更正它时,它不会再次获取结果吗?我猜onChange,你每次都会得到结果。
-
它应该再次获取结果,但是它没有。错误类型将数据设置为
[],但是当您删除错误类型时,数据仍然是[]。当我在键入过程中进行控制台日志时,在删除错误类型后会发生什么情况,它会返回到else if(Array.isArray(filteredName))但是,没有数据用于将状态重置为或类似的东西 -
可能你需要调整你的条件顺序。我的意见是搜索并存储每次文本搜索更改的结果,而不是依赖以前的结果集。
标签: javascript reactjs react-native