亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對 React 狀態數組進行排序

對 React 狀態數組進行排序

拉丁的傳說 2022-11-11 13:30:29
我無法對存儲在反應掛鉤狀態中的對象數組進行排序。此數組在排序后提供給平面列表。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>物體的位置沒有變化。任何幫助將不勝感激
查看完整描述

2 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

好吧,經過 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);


查看完整回答
反對 回復 2022-11-11
?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

從代碼中不確定,但 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)

這樣做可以為您節省重新渲染,因為您不必設置狀態。


希望有幫助!


查看完整回答
反對 回復 2022-11-11
  • 2 回答
  • 0 關注
  • 219 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號