【发布时间】:2022-01-20 17:50:37
【问题描述】:
我正在使用 react-navigation 6 和 react-native CLI 来制作聊天应用程序。我想实现这个在每个聊天应用程序中都很常见的功能,当我们向某人发送消息,然后返回应用程序的主屏幕(所有对话 已列出),可以看到最后发送的消息。
就像我发送消息并按下后退按钮一样,它会将我导航到我所有对话所在的主屏幕,并且它应该更新我发送消息的对话。
我尝试了 route.params,但它给出了non-serializable values found 的警告。
另外,我听说将 setState 函数传递给子组件是非常糟糕的做法,因为它提到了here
我还尝试了 navigation_events 和 useEffect ,令我惊讶的是它也不起作用。 当我手动刷新屏幕或注销并登录时,它会完全刷新,但当我从应用程序返回时不会刷新。
React.useEffect(() => {
navigation.addListener('focus', e => {
fetchConvos();
});
return () => {};
}, []); //also tried [navigation] instead of []
const fetchConvos = () => {
fetch('http://localhost:15000/' + id + '/conversations', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
})
.then(res => res.json())
.then(received => {
if (received?.response !== false) {
setConversations(received);
}
});
};
我检查了id、received甚至setConversations,它们都在更新,但我的屏幕仍然呈现旧消息。
另外,我不想使用 Async Storage 或 redux 来解决这种简单的问题。
如果这还不够,我可以分享完整代码。
编辑 我想出了另一种更新它的方法可能有助于进一步澄清情况。
React.useEffect(() => {
navigation.addListener('focus', e => {
setConversations([]); //first setting convos to empty
fetchConvos(); //then fetching new data
});
return () => {};
}, []);
但是这种方法很慢,因为我要更新对话状态两次。
如果有人可以在这里帮助我,我将不胜感激。
【问题讨论】:
标签: reactjs react-native react-hooks react-navigation