GiftedChatで配列を回してチャット履歴を作る
完全に覚書き。Reactも書いたことねえからセットステイト周りで積んでた。一ヶ月ぶりに再チャレンジでできるようになった。dbからチャットの履歴を取得した程で。
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
export default class App extends React.Component {
state = {
messages:
[
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user:
{
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
],
}
componentWillMount() {
let texts = [
{
_id: 3,
text: 'Hello developer 3',
createdAt: new Date(),
user: {
_id: 1,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
{
_id: 4,
text: 'Hello developer 4',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
];
let texts2 = [
{
_id: 6,
text: 'Hello developer 6',
createdAt: new Date(),
user: {
_id: 1,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
];
texts = texts.concat(texts2);
var i;
var ii;
for (i = 7; i < 23; i++) {
//奇数の場合
if( ( i % 2 ) != 0 ) {
ii = 1
}
//偶数の場合
if( ( i % 2 ) == 0 ) {
ii = 2
}
let texts3 = [
{
_id: i,
text: 'Hello developer 6',
createdAt: new Date(),
user: {
_id: ii,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
];
texts = texts.concat(texts3);
}
this.setState({
messages: this.state.messages.concat(
texts
)
})
}
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages),
}))
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1,
}}
/>
)
}
}