Javascript .id}`} renderItem={({item})=>} />
快乐编码 我的搜索方法;来自@metehan senol 该算法的搜索方法可以简化,并且可以像这样进行证明Javascript .id}`} renderItem={({item})=>} />,javascript,reactjs,react-native,Javascript,Reactjs,React Native,快乐编码 我的搜索方法;来自@metehan senol 该算法的搜索方法可以简化,并且可以像这样进行证明 search = (searchText) => { const searched = searchText.toLowerCase(); this.setState(prevState => ({ searchText: searched, filteredData: prevState.data.filter(item => ite
search = (searchText) => {
const searched = searchText.toLowerCase();
this.setState(prevState => ({
searchText: searched,
filteredData: prevState.data.filter(item =>
item.description.toLowerCase().includes(searched)
),
}));
};
在React Native中为列表视图数据设置搜索栏筛选器
使用搜索栏过滤器在列表视图中进行实时搜索
- 我们将从网络调用加载列表,然后将其显示给用户
- 用户可以通过在TextInput中输入文本来搜索数据
- 插入文本后,将调用searchfilter函数 将列表数据与插入的数据进行比较,并生成新数据 来源
- 我们将更新附加到ListView的数据源
- 它将重新呈现列表,用户将能够看到 过滤数据
//这是在Listview上添加搜索栏过滤器的示例代码//
从“React”导入React,{Component};
//在我们的代码中导入react。
进口{
文本,
样式表,
看法
平面列表,
文本输入,
活动指示器,
警觉的,
}从“反应本机”;
//导入我们将要使用的所有组件。
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
//设置默认状态
this.state={isLoading:true,文本:''};
this.arrayholder=[];
}
componentDidMount(){
返回获取('https://jsonplaceholder.typicode.com/posts')
.then(response=>response.json())
.然后(responseJson=>{
这是我的国家(
{
孤岛加载:false,
数据来源:responseJson
},
函数(){
this.arrayholder=responseJson;
}
);
})
.catch(错误=>{
控制台错误(error);
});
}
SearchFilterFunction(文本){
//在textinput中传递插入的文本
const newData=this.arrayholder.filter(函数(项){
//为搜索栏中插入的文本应用过滤器
const itemData=item.title?item.title.toUpperCase():''.toUpperCase();
const textData=text.toUpperCase();
返回itemData.indexOf(textData)>-1;
});
这是我的国家({
//在数据源上设置筛选的新数据
//设置数据后,它将自动重新渲染视图
数据源:newData,
文本:文本,
});
}
ListViewItemSeparator=()=>{
//项目参数视图
返回(
);
};
render(){
if(此.state.isLoading){
//加载数据时加载视图
返回(
);
}
返回(
//使用textinput作为搜索栏显示的ListView
this.SearchFilterFunction(text)}
值={this.state.text}
underlineColorAndroid=“透明”
占位符=“在此处搜索”
/>
(
{item.title}
)}
enableEmptySections={true}
style={{marginTop:10}}
keyExtractor={(项,索引)=>index.toString()}
/>
);
}
}
const styles=StyleSheet.create({
视图样式:{
为内容辩护:“中心”,
弹性:1,
玛金托普:40,
填充:16,
},
文本样式:{
填充:10,
},
文本输入样式:{
身高:40,
边框宽度:1,
paddingLeft:10,
边框颜色:'#009688',
背景颜色:“#FFFFFF”,
},
});代码>通过应用
let filterData= data.filter((item) => {
return item.name.toLowerCase().match(text)
})
if (!text || text === '') {
this.setState({
datasource: initial
})
} else if (!Array.isArray(filterData) && !filterData.length) {
// set no data flag to true so as to render flatlist conditionally
this.setState({
noData: true
})
} else if (Array.isArray(filterData)) {
this.setState({
noData: false,`enter code here`
dataSource: filterData
})`enter code here`
}
就性能而言,这不是最好的解决方案,但如果您没有大量数据,请随意使用此功能:
searchText = (e) => {
let text = e.toLowerCase()
let trucks = this.state.data
let filteredName = trucks.filter((item) => {
return item.name.toLowerCase().match(text)
})
if (!text || text === '') {
this.setState({
data: initial
})
} else if (!Array.isArray(filteredName) && !filteredName.length) {
// set no data flag to true so as to render flatlist conditionally
this.setState({
noData: true
})
} else if (Array.isArray(filteredName)) {
this.setState({
noData: false,
data: filteredName
})
}
}
searchFilter () {
return this.props.data.filter((item) => {
const regex = new RegExp(this.state.searchInput, "gi")
return item.label.match(regex);
})
}
然后在平面列表组件中:
<FlatList
data={this.searchFilter()}
renderItem={this.renderItem}
keyExtractor={(item) => item.value}
/>
item.value}
/>
您可以通过以下步骤搜索数据:
<TextInput onChangeText={(text) => searchData(text)} value={input} />
注意RestaurantsData是我的数据数组有什么问题?当用户修改搜索文本时,是否没有重新呈现?@Umesh问题是,当用户输入错误时,数据被设置为[]
,然后当他们删除错误输入时,数据应该重置回搜索的最后状态…只是还没有弄清楚这可能如何工作。可能是设置了前一个状态,然后以某种方式调用它?当用户键入错误时,结果为空[],但当用户更正它时,它不会再次获取结果吗?我猜一旦更改,您每次都会得到结果。它应该再次获取结果,但是,它不会。错误类型将数据设置为[]
,但删除错误类型时,数据仍然是[]
。当我在输入过程中记录日志时,删除错误类型后会返回到否则如果(Array.isArray(filteredName))
但是,没有数据可以将is重置为或类似的状态。您可能需要调整条件顺序。我的意见是搜索和存储每次文本搜索更改的结果,而不是依赖以前的结果集。你们有这个解决方案的github链接吗?不适合我,当我做卡车控制台时。filter((item)=>{console.log(item)}它在item.name.toLowerCase()中给出“message:“item is not defined”(项目未定义))如果您将正在筛选的数据记录在控制台日志中,那么也会出现错误。您是否在其中获得任何数据?是否确实需要传递this.props.noData
?仅检查if(this.props.data)
this.state = {
data: [],
backup: []
}
search = txt => {
let text = txt.toLowerCase()
let tracks = this.state.backup
let filterTracks = tracks.filter(item => {
if(item.name.toLowerCase().match(text)) {
return item
}
})
this.setState({ data: filterTracks })
}
constructor(props) {
super(props);
this.state = {
data: [],
value: ""
};
this.arrayholder = [];
}
_fetchdata = async () => {
const response = await fetch("https://randomuser.me/api?results=10");
const json = await response.json();
this.setState({ data: json.results });
this.arrayholder = json.results;
};
searchFilterFunction = text => {
this.setState({
value: text
});
const newData = this.arrayholder.filter(item => {
const itemData = item.email.toLowerCase();
const textData = text.toLowerCase();
return itemData.indexOf(textData) > -1;
});
this.setState({ data: newData });
};
<TextInput
style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
onChangeText={text => this.searchFilterFunction(text)}
/>
this.state = {
searchText: "",
data: [],
filteredData: []
};
<SearchBar
round={true}
lightTheme={true}
placeholder="Search..."
autoCapitalize='none'
autoCorrect={false}
onChangeText={this.search}
value={this.state.searchText}
/>
search = (searchText) => {
this.setState({searchText: searchText});
let filteredData = this.state.data.filter(function (item) {
return item.description.includes(searchText);
});
this.setState({filteredData: filteredData});
};
<FlatList
data={this.state.filteredData && this.state.filteredData.length > 0 ? this.state.filteredData : this.state.data}
keyExtractor={(item) => `item-${item.id}`}
renderItem={({item}) => <ListItem
id={item.id}
code={item.code}
description={item.description}
/>}
/>
search = (searchText) => {
this.setState({searchText: searchText});
let filteredData = this.state.data.filter(function (item) {
return item.description.includes(searchText);
});
this.setState({filteredData: filteredData});
};
search = (searchText) => {
const searched = searchText.toLowerCase();
this.setState(prevState => ({
searchText: searched,
filteredData: prevState.data.filter(item =>
item.description.toLowerCase().includes(searched)
),
}));
};
let filterData= data.filter((item) => {
return item.name.toLowerCase().match(text)
})
if (!text || text === '') {
this.setState({
datasource: initial
})
} else if (!Array.isArray(filterData) && !filterData.length) {
// set no data flag to true so as to render flatlist conditionally
this.setState({
noData: true
})
} else if (Array.isArray(filterData)) {
this.setState({
noData: false,`enter code here`
dataSource: filterData
})`enter code here`
}
searchFilter () {
return this.props.data.filter((item) => {
const regex = new RegExp(this.state.searchInput, "gi")
return item.label.match(regex);
})
}
<FlatList
data={this.searchFilter()}
renderItem={this.renderItem}
keyExtractor={(item) => item.value}
/>
<TextInput onChangeText={(text) => searchData(text)} value={input} />
***Please Note *searchData is my function whom I passing a text prop***
const searchData = (text) => {
const newData = restaurantsData.filter((item) => {
return item.title.search(text) > -1;
});
setRestaurantsData(newData);
setInput(text);
};