gpt4 book ai didi

javascript - 执行连接时来自 firebase 的数据排序不正确

转载 作者:行者123 更新时间:2023-11-30 20:22:04 24 4
gpt4 key购买 nike

我正在尝试从 firebase 获取按时间顺序排列的数据。我正在使用 .push 来存储数据,所以它应该按时间顺序给我数据,当我不执行“加入”时,它可以正常工作。

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}
/>
);
}
};

这是截图: Screenshot of the rendered Chat-Component

最佳答案

您可以等待所有 firebase promise 解决,然后在发送 GET_MESSAGE_SUCCESS 之前对您的 msgArray 进行排序

示例

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));
});
};

关于javascript - 执行连接时来自 firebase 的数据排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51341672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com