【发布时间】:2022-02-17 13:54:03
【问题描述】:
我正在开发一个较大的 React Native 应用程序的聊天室部分,并且在发送文本后面临更新页面的问题。当前,当用户在TextInput 中编译文本并点击发送按钮时,它会触发一个突变,该突变应该将message 对象添加到chatroom 模型,该模型链接到所有users当前在聊天室中。然后它应该从这个突变中获取结果,即更新的chatroom 连接到所有users(显然包括当前用户)并渲染其内容。它旨在在更新activeThread 原子后重新呈现页面,因为该页面使用activeThread 的内容来呈现页面上的所有内容,包括新消息。然而,这是异步发生的,它试图呈现一个承诺......这是你做不到的。我已经尝试了我能做的所有事情,在任何我可以使用的地方使用thens 和awaits,但是 JavaScript 在这方面给了我很大的中指。我的代码在下面...
const handleSendMessage = async () => {
console.log(activeThread.id)
if (newMessage.length > 0){
return sendMessage({
variables: {
chatroomId: activeThread.id,
content: newMessage
}
}).then( async (newMessageThread) => {
await setUpdating(true)
await setNewMessage("")
await setKeyboardVisible(false);
await setActiveThread(newMessageThread)
}).then( async() => {
await console.log(activeThread)
await setUpdating(false)
})
}
else{
}
}
setUpdating 是 useState 的一部分。这默认为false,并且当true 未将主页设置为呈现时。它旨在防止试图兑现承诺。显然没用
setNewMessage 默认为"",负责跟踪用户在TextInput 中输入的文本。在这里完全无关紧要。
setKeyBoardVisible 很容易解释,也没有必要
setActiveThread 是这里的重担。几乎所有呈现的内容都将从activeThread 提取数据,这又是一次;一种反冲状态。例如,下面的所有内容看起来都类似于
<View>
<Text> {activeThread.someMethodOrValue} </Text>
</View>
我只能假设这与异步有关。我的后端 GraphQL 突变解析器中有一个 console.log(error) 语句,它可以捕获那里的任何错误,并且它不会触发任何东西。我每次得到的错误如下......
TypeError: undefined is not an object (evaluating 'activeThread.chatroomName.split')
This error is located at:
in MessageThread (created by SceneView)
in StaticContainer
in EnsureSingleNavigator (created by SceneView)
in SceneView (created by SceneView)
in {/* keeps going down the stack you get the idea */}
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'activeThread.chatroomName.split')]
at Pages/CommunicationPage/MessageThread.js:210:37 in MessageThread
有什么解决办法吗?
【问题讨论】:
标签: react-native asynchronous async-await graphql recoiljs