gpt4 book ai didi

javascript - Array.sort 在控制台中有效,但在 React Native 应用程序中无效

转载 作者:行者123 更新时间:2023-11-29 10:04:08 25 4
gpt4 key购买 nike

我正在使用 GiftedChat 使用 React-Redux 构建一个内部消息传递应用程序来显示我的消息。然而,它们总是按错误的时间顺序排列。所以我想我会在我看来对数组进行排序。但是,它似乎没有用,我也不知道为什么。这就是它的样子(为简单起见缩短):

class MessageView extends React.Component {
onSend (messages = []) {
// ...
}

render () {
return (
<GiftedChat
messages={this.props.messages}
onSend={(messages) => this.onSend(messages)}
user={{ _id: this.props._id }}
/>
)
}
}

const mapStateToProps = (state, ownProps) => {
var msgs = state.inboxReducer.myinbox.find(item =>
item.owner_id === ownProps.navigation.state.params.owner_id).messages

msgs = msgs.sort((a, b) => {
return new Date(a.createdAt) - new Date(b.createdAt)
})

return {
messages: msgs,
_id: state.user._id
}
}

export default connect(mapStateToProps, {})(MessageView)

这是消息数组的示例(从我的初始状态):

[{
_id: 1,
text: 'Hey whats goin on mate?',
createdAt: new Date(Date.UTC(2017, 10, 11, 11, 20, 0)),
user: {
_id: 1,
name: 'John Lennon'
}
},
{
_id: 2,
text: 'Just working on the next album.',
createdAt: new Date(Date.UTC(2017, 10, 11, 11, 25, 0)),
user: {
_id: 2,
name: 'Paul McCartney'
}
},
{
_id: 3,
text: 'Great, I will be in the studio later.',
createdAt: new Date(Date.UTC(2017, 10, 11, 11, 31, 0)),
user: {
_id: 1,
name: 'John Lennon'
}
}]

令我感到困惑的是,如果我将它放在 chrome 调试控制台中,排序工作正常。事实上,我在不同的 React 组件中使用完全相同的排序来获取聊天收件箱的最新消息,这工作很好。

const mapStateToProps = (state) => {
return {
inbox: state.inboxReducer.myinbox.map((x) => {
let msg = x.messages.sort((a, b) => {
return new Date(a.createdAt) - new Date(b.createdAt)
}).slice(-1)[0]
return ({
_id: x._id,
name: x.name,
message: msg
})
})
}
}

有没有人见过 Array.sort() 在某些 React 上下文中起作用但在其他上下文中不起作用的时候?

最佳答案

尽量避免在 React Native 中使用 new Date()。取而代之的是使用像我们这样的库来解决它引起的很多问题。我遇到了类似的问题,我的排序在模拟器上有效,但在设备上无效。

//DIDN'T WORK ON DEVICE
const sortedPointsByDate = filteredPoints.sort((a,b)=> new Date(b.logDate) - new Date(a.logDate))

//WORKED ON BOTH
const sortedPointsByDate = filteredPoints.sort((a,b)=> moment(b.logDate) - moment(a.logDate))

我建议尝试用 moment() 替换所有新的 Date() 实例

关于javascript - Array.sort 在控制台中有效,但在 React Native 应用程序中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com