第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

對(duì) React 狀態(tài)數(shù)組進(jìn)行排序

對(duì) React 狀態(tài)數(shù)組進(jìn)行排序

拉丁的傳說(shuō) 2022-11-11 13:30:29
我無(wú)法對(duì)存儲(chǔ)在反應(yīng)掛鉤狀態(tài)中的對(duì)象數(shù)組進(jìn)行排序。此數(shù)組在排序后提供給平面列表。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>物體的位置沒(méi)有變化。任何幫助將不勝感激
查看完整描述

2 回答

?
函數(shù)式編程

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊

好吧,經(jīng)過(guò) 4-6 小時(shí)的嘗試,我終于找到了解決方案。問(wèn)題源于 ECMAScript 時(shí)間戳格式。


我的時(shí)間戳格式:“YYYY-MM-DD HH:MM:SS”


支持的 ECMAScript 時(shí)間戳:“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);


查看完整回答
反對(duì) 回復(fù) 2022-11-11
?
慕村9548890

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊

從代碼中不確定,但 notification.created_at 是什么?那是在epochmilli嗎?它只是一個(gè)數(shù)字嗎?如果是這樣,則無(wú)需將其轉(zhuǎn)換為日期,然后運(yùn)行 .getTime()。您應(yīng)該能夠?qū)?x.created_at - y.created_at 進(jìn)行排序。這可能就是問(wèn)題所在。


此外,順便說(shuō)一句,您可以將此代碼簡(jiǎn)化為:


const { notifications } = useContext(MainContext);

const sortedNotification = [...notifications].sort((x, y) => x.created_at - y.created_at);


return (... your view)

這樣做可以為您節(jié)省重新渲染,因?yàn)槟槐卦O(shè)置狀態(tài)。


希望有幫助!


查看完整回答
反對(duì) 回復(fù) 2022-11-11
  • 2 回答
  • 0 關(guān)注
  • 217 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)