我正在使用react-native-gifted-chat(https://github.com/FaridSafi/react-native-gifted-chat)在我的应用程序上创建一个聊天界面,我想从数据库中加载消息。
我正在使用领域,并且能够加载数据,但是下面的代码仅加载数据的第一行。我希望能够从数据库中加载所有数据。
let chatData = realmDatabase.objects(DatabaseTableNames.chatTable);
let data=[];
for (let message of chatData ){
data = [{
_id: message.chatUniqueID,
text: message.msgBody,
createdAt: (new Date()).getTime(),
user: {
_id: message.chatUniqueID,
name: message.senderName
}
} ]
}
console.log(data)
我希望能够从数据库中不仅加载第一行中的所有数据,如下面的示例一样。
[
{
_id: Math.round(Math.random() * 1000000),
text:
"It uses the same design as React, letting you compose a rich mobile UI from declarative components https://facebook.github.io/react-native/",
createdAt: new Date(Date.UTC(2016, 7, 31, 17, 20, 0)),
user: {
_id: 1,
name: "Developer"
},
},
{
_id: Math.round(Math.random() * 1000000),
text: "React Native lets you build mobile apps using only JavaScript",
createdAt: new Date(Date.UTC(2016, 7, 30, 17, 20, 0)),
sent: true,
received: true,
user: {
_id: 2,
name: "Developer"
},
}
];
答案 0 :(得分:2)
在for循环中执行data = [{...}]
,会将message
的最后一个值分配给data
。要获取所有值,需要push data
数组中的项目。您可以这样做:
let chatData = realmDatabase.objects(DatabaseTableNames.chatTable);
let data=[];
for (let message of chatData ){
data.push({
_id: message.chatUniqueID,
text: message.msgBody,
createdAt: (new Date()).getTime(),
user: {
_id: message.chatUniqueID,
name: message.senderName
}
});
}
console.log(data)