2017-11-26 8 views
3

GiftedChatを使用してReact-Reduxで内部メッセージングアプリを構築しています。しかし、彼らは常に間違った年代順です。だから私は私の視点で配列を並べ替えると思う。しかし、それは動作していないようで、私は理由を理解できません。これは、(簡単にするために短縮)のようになります。Array.sortはコンソールで動作しますが、ネイティブアプリではありません

[{ 
    _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' 
    } 
}] 

何私の心をbogglesがあればということである。ここでは

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) 

は、メッセージの配列は、(私の初​​期状態から)どのように見えるかの例です私はこれをChromeのデバッグコンソールに入れて、ソーティングはうまく動作します。実際には、別のリアクションコンポーネントで同じ正確な並べ替えを使用して、チャットの受信トレイの最新のメッセージを取得します。この はうまく動作します。

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コンテキストでは動作するが、他のコンテキストでは動作しない人は誰も見たことがありますか?

+2

上記の非動作コードに 'messages:newmsgs'を返します。 'newmsgs'はどこから来たのですか? –

答えて

1

あなたは常にそれを後悔しますので、クライアント/ブラウザで並べ替えや検索を実行する誘惑に常に抵抗してください。後であなたはより高度なソートをするでしょう。何らかの理由でそれをすべて放棄しなければならなくなるでしょう。私を信じて。情報をソートする必要がある場合は、DBにそれをさせてください!申し訳ありませんが説教を鳴らすが、それは本当にあなたのための最高の答えです。

+0

良いアドバイス – Andrew

+0

全く説教していません。非常に良いアドバイス。私はそうするだろう。私はまだ1つのメソッドで動作するArray.sortに悩まされていますが、別の方法ではうんざりです。 – RedOster

+0

@RedOsterソートを解決するには(JSON.stringifyを使用してソートの前後にコンソールにリストを記録して、それを勉強することができます)私はそれが配列の場所をソートするかどうか、またはソートされた新しい配列を返すかどうか覚えていませんが、コンソールに両方を記録すると、あなたはそれを理解するでしょう。 –

関連する問題