【问题标题】:Sorting React State Array对 React 状态数组进行排序
【发布时间】:2020-07-11 17:42:53
【问题描述】:

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

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>

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

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    从代码中不确定,但 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)
    

    这样做可以节省重新渲染,因为您不必设置状态。

    希望有帮助!

    【讨论】:

      【解决方案2】:

      好吧,经过 4-6 小时的尝试,我终于找到了解决方案。 问题源于 ECMAScript 时间戳格式。

      我的时间戳格式:“YYYY-MM-DD HH:MM:SS”

      支持的 ECMAScript 时间戳:“YYYY-MM-DDTHH:MM:SS” - “T”

      工作代码:

      const sorted = notifications.slice().sort((x, y) => {
            var dateStringX = x.created_at.replace(" ", "T");
            var dateStringY = y.created_at.replace(" ", "T");
                  
            return new Date(dateStringY).getTime() - new Date(dateStringX).getTime(); 
      });
      
      setNotifications(sorted);
      

      【讨论】:

        猜你喜欢
        • 2020-06-25
        • 2019-04-27
        • 2016-03-04
        • 2021-06-05
        • 2019-11-22
        • 1970-01-01
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多