[英]Why sorting of the Flatlist is not appearing? in react native
我目前正在按升序和降序进行排序,但没有出现平面列表。
我想通过每个单独的按钮显示最近添加的排序顺序,从低到高和从高到低。
请帮忙。
下面是我的代码:
const [ demoList, setdemoList ] = useState([
{id: 3, name: 'Omkar'},
{id: 2, name: 'Abhishek'},
{id: 1, name: 'Saurabh'},
{id: 1, name: 'Saurabh'},
{id: 4, name: 'Chintan'},
{id: 6, name: 'Hardik'},
{id: 5, name: 'Lalit'},
]);
const sortListById = () => {
demoList.sort(function (obj1, obj2) {
return obj1.id - obj2.id;
});
};
return (
<View style={styles.container}>
<View style={{ margin: 10,alignItems: 'center',justifyContent: 'center',}}>
<FlatList data={demoList}
extraData={setdemoList}
renderItem={({ item }) => (
<View style={{ flexDirection: 'row' }}>
<Text style={{ fontSize: 20, margin: 15 }}>{item.id}</Text>
<Text style={{ fontSize: 20, margin: 15 }}>{item.name}</Text>
</View>
)}
keyExtractor={(item, index) => index}
/>
<View style={{ flex: 1 }}>
<Button title="Sort List" onPress={sortListById} />
</View>
</View>
</View>
);
工作示例: Expo Snack ,在这里您可以按 ASC 和 DEC 顺序排序。
Output:
解决方案:
import React, { useState } from 'react';
import { StyleSheet, Text, View, FlatList, Button } from 'react-native';
let data = [
{ id: 3, name: 'Omkar' },
{ id: 2, name: 'Abhishek' },
{ id: 1, name: 'Saurabh' },
{ id: 1, name: 'Saurabh' },
{ id: 4, name: 'Chintan' },
{ id: 6, name: 'Hardik' },
{ id: 5, name: 'Lalit' },
];
export default function Home() {
const [demoList, setdemoList] = useState([...data]);
const [order, setOrder] = useState(1);
const sortListASC = () => {
demoList.sort((obj1, obj2) => {
return obj1.id - obj2.id;
});
setdemoList([...demoList]); // update
};
const sortListDES = () => {
demoList.sort((obj1, obj2) => {
return obj2.id - obj1.id;
});
setdemoList([...demoList]);
};
return (
<View style={styles.container}>
<View
style={{ margin: 10, alignItems: 'center', justifyContent: 'center' }}>
<FlatList
data={demoList}
renderItem={({ item }) => (
<View style={{ flexDirection: 'row' }}>
<Text style={{ fontSize: 20, margin: 15 }}>{item.id}</Text>
<Text style={{ fontSize: 20, margin: 15 }}>{item.name}</Text>
</View>
)}
keyExtractor={(item, index) => index}
/>
<View style={{ flex: 1, flexDirection: 'row' }}>
<View style={{ marginLeft: 10 }}>
<Button title={'ASC'} onPress={sortListASC} />
</View>
<View style={{ marginLeft: 10 }}>
<Button title={'DEC'} onPress={sortListDES} />
</View>
<View style={{ marginLeft: 10 }}>
<Button title={'Default'} onPress={() => setdemoList([...data])} />
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
使用它来避免数据突变。
const sortListById = () => setdemoList([...demoList].sort( (obj1, obj2)=>obj1.id - obj2.id))
如果你使用这个
demoList.sort((obj1, obj2) =>{
return obj1.id - obj2.id;
});
这将改变demoList
的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.