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

标签 javascript arrays sorting react-native

我正在使用 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/

相关文章:

javascript - 如何根据页面是否滚动到顶部来修改类?

arrays - Powershell - 将 CSV 文件加载到多维数组中

java - 如何在保持排序的同时将排序的链表插入另一个排序的链表?

iphone - iOS 使用冒泡排序排序但最后一行未排序

c - 在 C 中对数组进行排序?

javascript - 在随机位置开始 HTML5 <Audio>

java - jsf 2.0 (myfaces) 中的 ajax 调用,在渲染完成之前调用 ajax 标记中的 onevent Javascript 函数

javascript - 触发引导模式隐藏 (hide.bs.modal) 事件后,$location.path 需要一些时间才能工作

php - 如何在 php 中执行模式为数组的 preg_match?

javascript - 在 Typescript 2 中,如何从对象数组中获取单个属性并分配给新数组?