对 React 状态数组进行排序

我无法对存储在反应挂钩状态中的对象数组进行排序。此数组在排序后提供给平面列表。


const { notifications } = useContext(MainContext);

const [sortedNotifications, setSortedNotifications] = useState([]);


useEffect(() => {

    setSortedNotifications(

        [...notifications].concat([]).sort(function(x, y){

            return new Date(y.created_at).getTime() - new Date(x.created_at).getTime();

        })

    )

}, [notifications]);


return <View style={{ flex: 1,  backgroundColor: "white", }}>

    {notifications !== null && notifications.length > 0 ? <FlatList 

        vertical

        contentContainerStyle={{ paddingRight: 20, paddingLeft: 20, paddingBottom: 20, paddingTop: 20}}

        showsVerticalScrollIndicator={false}

        style = {styles.flatListStyle}

        data = {sortedNotifications} 

        keyExtractor = {(item,i) => `key-${item.title}-${i}`}

        renderItem = {({ item }) => {

        return <TouchableOpacity activeOpacity={0.8} style={styles.viewStyle} onPress={() => props.navigation.navigate("Notification", { n: item })}>

                <Text style={styles.textStyle}>{Capitalize(item.title)}</Text>

                <Text style={styles.text2Style}>Received {moment.utc(item.created_at).fromNow()}</Text>

        </TouchableOpacity>

    }}></FlatList> : <View></View>}

</View>

物体的位置没有变化。任何帮助将不胜感激


拉丁的传说
浏览 253回答 2
2回答

函数式编程

好吧,经过 4-6 小时的尝试,我终于找到了解决方案。问题源于 ECMAScript 时间戳格式。我的时间戳格式:“YYYY-MM-DD HH:MM:SS”支持的 ECMAScript 时间戳:“YYYY-MM-DDTHH:MM:SS” - “T”工作代码:const sorted = notifications.slice().sort((x, y) => {&nbsp; &nbsp; &nbsp; var dateStringX = x.created_at.replace(" ", "T");&nbsp; &nbsp; &nbsp; var dateStringY = y.created_at.replace(" ", "T");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; return new Date(dateStringY).getTime() - new Date(dateStringX).getTime();&nbsp;});setNotifications(sorted);

慕村9548890

从代码中不确定,但 notification.created_at 是什么?那是在epochmilli吗?它只是一个数字吗?如果是这样,则无需将其转换为日期,然后运行 .getTime()。您应该能够对 x.created_at - y.created_at 进行排序。这可能就是问题所在。此外,顺便说一句,您可以将此代码简化为:const { notifications } = useContext(MainContext);const sortedNotification = [...notifications].sort((x, y) => x.created_at - y.created_at);return (... your view)这样做可以为您节省重新渲染,因为您不必设置状态。希望有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript