您好 StackOverflow 社區的同胞,我在 Next.js 應用程式中嘗試.map()使用getDoc()常量時遇到了一個錯誤,提示如下:“TypeError: Cannot read properties of undefined (reading 'map')”。我是 Next.js 的新手,非常感謝社區提供的任何幫助。很長一段時間以來,我一直在嘗試在互聯網上搜索答案,但什么也沒有。
在這里您可以查看以下代碼[id].js:
import styled from "styled-components";
import Head from "next/head";
import Sidebar from "../components/Sidebar";
import ChatScreen from "../components/ChatScreen";
import { db } from "../../firebase";
import { collection, doc, orderBy, getDoc } from "firebase/firestore";
const Chat = () => {
return (
<Container className="bg-stone-900">
<Head></Head>
<Sidebar />
<ChatContainer>
<ChatScreen />
</ChatContainer>
</Container>
);
};
export default Chat;
export async function getServerSideProps(context) {
const ref = doc(collection(db, "chats"), context.query.id);
const messagesRes = await getDoc(
ref,
collection(db, "messages"),
orderBy("timestamp", "asc")
);
const messages = messagesRes.docs
.map((doc) => ({ //Here is the error line.
id: doc.id,
...doc.data(),
}))
.map((messages) => ({
...messages,
timestamp: messages.timestamp.toDate().getTime(),
}));
const chatRes = await getDoc();
const chat = {
id: chatRes.id,
...chatRes.data(),
};
return {
props: {
messages: JSON.stringify(messages),
chat: chat,
},
};
}
const Container = styled.div`
margin: 0 auto;
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
`;
const ChatContainer = styled.div`
margin: 0 auto;
overflow: scrollbar;
`;
再次感謝您的任何回答!
uj5u.com熱心網友回復:
如果您嘗試遍歷 docs 陣列,它應該是getDocs,您不能使用 getDoc 回圈,因為它只回傳一個不是陣列的檔案,因此您會得到未定義的原因。
您可以嘗試使用下面的代碼來回圈使用getDocs的訊息
const ref = doc(collection(db, "chats"), context.query.id);
const messagesRes = await getDocs(
ref,
collection(db, "messages"),
orderBy("timestamp", "asc")
);
uj5u.com熱心網友回復:
這個問題對于我們很多剛起步的人來說是一場噩夢。我知道我也為此苦苦掙扎。也就是說,資料快照回傳一個 json 物件。.map() 函式用于陣列。因此必須對其進行操作,以便地圖知道如何迭代它。
每 w3
array.map(function(currentValue, index, arr), thisValue).
所以你的
data.map(Object.entries(JSON.parse(data)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/530736.html
標籤:Google Cloud Collective javascript数据库火力基地下一个.js
上一篇:Postgres Go Docker-compose無法ping資料庫:撥號tcp127.0.0.1:5432:連接:連接被拒絕
