我正在尝试从Firebase按时间顺序获取数据。我正在使用.push来存储数据,因此它应该按时间顺序为我提供数据,并且当我不执行“ join”时,它可以正常工作。
export const getMessages = (groupId) => (dispatch) => {
dispatch({ type: GET_MESSAGES });
firebase.database().ref(`/chats/${groupId}/messages`)
.on('value', snapshot => {
msgArray = [];
snapshot.forEach((child) => {
let children = child.val();
// join to get the name
firebase.database().ref(`/users/${children.from}/`)
.once('value', snap => {
children.creatorName = snap.val().name;
msgArray.unshift(children);
})
.then(() => {
dispatch({ type: GET_MESSAGES_SUCCESS, payload: msgArray });
})
.catch((e) => console.log(e));
});
});
};
我渲染时的结果是这样的:
Max - 2 hours ago - Hello
Max - 3 hours ago - How are you?
Max - 4 hours ago - What's up
Max - 5 hours ago - ...
Alex - 2 hours ago - Hello
Alex - 3 hours ago - Fine thank you
Alex - 4 hours ago - What's up
Alex - 5 hours ago - ...
但是应该像这样:
Max - 2 hours ago - Hello
Alex - 2 hours ago - Hello
Max - 3 hours ago - How are you?
Alex - 3 hours ago - Fine thank you
...
我在这里做什么错了?
这是我渲染的地方:
renderItem = ({ item }) => {
if (item.from === this.props.userKey) {
return (
<OwnMessage
time={moment(item.timestamp).fromNow()}
messageText={item.messageText}
from={item.creatorName}
/>
);
} else {
return (
<OthersMessage
time={moment(item.timestamp).fromNow()}
messageText={item.messageText}
from={item.creatorName}
/>
);
}
};
答案 0 :(得分:1)
您可以等待所有firebase承诺解决,然后sort
msgArray
,然后再分发GET_MESSAGE_SUCCESS
。
示例
export const getMessages = groupId => dispatch => {
dispatch({ type: GET_MESSAGES });
firebase
.database()
.ref(`/chats/${groupId}/messages`)
.on("value", snapshot => {
const promises = [];
snapshot.forEach(child => {
const children = child.val();
const promise = firebase
.database()
.ref(`/users/${children.from}/`)
.once("value")
.then(snap => {
children.creatorName = snap.val().name;
return children;
});
promises.push(promise);
});
Promise.all(promises)
.then(msgArray => {
msgArray.sort((a, b) => {
if (a.timestap < b.timestamp) {
return -1;
} else if (a.timestamp > b.timestamp) {
return 1;
} else {
return 0;
}
});
dispatch({ type: GET_MESSAGES_SUCCESS, payload: msgArray });
})
.catch(e => console.log(e));
});
};