我正在撰寫一個聊天應用程式。用戶可以搜索其他用戶,然后按“訊息”按鈕。然后我導航到ChatScreen.js. 如果兩個用戶都在互相發送訊息,我會chatId相應地設定變數。如果他們在我不創建之前沒有互相chatId發送訊息,直到發送了第一條訊息。發送第一條訊息時,我首先創建新聊天,將其屬性(用戶 ID、聊天 ID 等)存盤在我的資料庫中,然后發送第一條訊息。問題是我存盤chatId為狀態變數,當我創建聊天時我呼叫setChatId(id). setChatId()不是同步呼叫,所以當我需要與sendText(text, chatId);我發送訊息chatId時,undefined即使我已經創建了一個聊天并且我已經呼叫了setChatId.
我怎樣才能避免這個錯誤?Ofc,我可以檢查if chatId == undefined然后呼叫sendText(text, id),否則呼叫sendText(text, chatId)。有沒有更好/最有效的方法來避免undefined檢查?
這是我的代碼的一部分:
...
import {
createChat,
} from "./actions";
...
function ChatScreen(props) {
...
const [chatId, setChatId] = useState(props.route.params.chatId);
...
const setupChat = async () => {
try {
await createChat(user.id, setChatId);
props.fetchUserChats();
} catch (error) {
console.error("Error creating chat: ", error);
}
};
async function handleSend(messages) {
if (!chatId) {
// creating chat
await setupChat();
}
const text = messages[0].text ? messages[0].text : null;
const imageUrl = messages[0].image ? messages[0].image : null;
const videoUrl = messages[0].video ? messages[0].video : null;
const location = messages[0].location ? messages[0].location : null;
//assuming chatId is already setup but it is not
if (imageUrl) {
sendImage(imageUrl, chatId, setSendImageError);
} else if (location) {
sendLocation(location, chatId, setLocationError);
} else if (videoUrl) {
sendVideo(videoUrl, chatId, setSendImageError);
} else {
sendText(text, chatId);
}
}
...
}
我的檔案createChat功能actions.js
export async function createChat(otherUid, setChatId) {
let chatId = firebase.auth().currentUser.uid "_" otherUid;
await firebase
.firestore()
.collection("Chats")
.doc(chatId)
.set({
users: [firebase.auth().currentUser.uid, otherUid],
lastMessage: "Send the first message",
lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp(),
})
.then(() => {
console.log("doc ref for creatign new chat: ", chatId);
setChatId(chatId);
})
.catch((error) => {
console.error("Error creating chat: ", error);
});
}
uj5u.com熱心網友回復:
我建議您不要使用狀態變數,而是使用useRef(). 這將是您問題的一個很好的解決方案。例如,以這種方式定義它
const chatId = useRef(null),
然后這樣設定chatId.current = yourChatId
并以這種方式得到它chatId.current。我希望這能解決你的問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436563.html
