web-dev-qa-db-ja.com

react-native-gifted-chatがFirebaseタイムスタンプの時間を正しく表示しないのはなぜですか?

アプリで react-native-gifted-chat を使用してチャット機能を追加しました。現在、firebaseと適切にメッセージを送受信できています。しかし、問題はreact-native-gifted-chatは常にメッセージ送信時刻の午前12時を表示します。これは、firebaseタイムスタンプを時間に変換できないためです。誰でも私を助けてくれますか?

GiftedChatコンポーネントの使用方法は次のとおりです。

<GiftedChat
  messages={this.props.messages}
  renderUsernameOnMessage={true}
  onSend={messages => this.onSend(messages)}
  alwaysShowSend={true}
  textInputStyle={styles.composer}
  minComposerHeight={40}
  minInputToolbarHeight={60}
  user={{
    _id: this.props.account ?.user ?.uid,
    name: this.props.account ?.data ?.fullName,
    avatar: this.props.account ?.data ?.avatar
  }}
/>

以下は、firestoreにメッセージを保存するために使用したコードです。

export const sendMessage = (message, groupId) => {
  return async () => {
    await firestore().collection('groupMessages').doc(groupId).collection('messages').doc(message._id).set(message).catch((e) => {
      throw {message: e.message.replace(`[${e.code}] `, '')}
    });
  }
}

上記のコードでmessageは、プロパティを含むギフト付きのチャットメッセージです:_idtextcreatedAtおよびuser

メッセージがfirebaseに保存される方法は次のとおりです。

Firebase message structure

メッセージを表示すると:

Message

3
Kishan Bharda

最後に、一時的なソリューションで完了しました。 renderTimeの小道具で時間をカスタムとしてレンダリングすることで解決します。

_<GiftedChat
  ...
  renderTime={(props) => (
    <View style={props.containerStyle}>
      <CText size={10} style={{marginHorizontal: 10, marginBottom: 5}} bold color={props.position === "left" ? 'gray' : 'white'}>
        {`${props.currentMessage.createdAt.toDate().toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true })}`}
      </CText>
    </View>
  )}
  ...
  ...
/>
_

私はcreatedAtを日付に変換し、それをhh:mm AM/PMギ酸で取得しました。

注: GiftedChatが生成したメッセージフィールドcreatedAttoDate()関数なので、このタイプのエラーが発生する可能性があります。

Uncaught TypeError:(中間値).toDateは:1:12の関数ではありません

2
Kishan Bharda

私の個人的な経験から、これを解決する最も簡単な方法は、createdAt時間プロパティをmillisecondsに変換してから、Date.parse()メソッドを使用してデータをfirebaseに保存することです。なので react-native-gifted-chat異なる時間プロパティ形式でmessageオブジェクトを生成します。つまり"createdAt": 2020-05-08T06:56:44.698Z。ただし、このプロパティをfirebaseに保存すると、timestampとして表示され、firebaseからデータをフェッチすると、プロパティcreatedAtが異なるフォーマット"createdAt": {"_nanoseconds": 943000000, "_seconds": 1588921685}。これにより問題が発生し、アプリは常に現在の日付と時刻を表示します12:00 AM。したがって、簡単な解決策は、日付形式を変更してから、Firebaseに保存することです。

const saveMessage = async (message) => {
    const temp = message[0];

    const createdAt = Date.parse(temp.createdAt); //<--- add this line

    const a = await db.add({ ...temp, createdAt });

    //---------your other code--------//
  }

これで、firebaseからデータをフェッチするときに、アプリに正しい日付と時刻が表示されます。

2
Aoun