这是我正在尝试做的事情的示例:
import { useRouter } from "next/router";
import { useCollection } from "react-firebase-hooks/firestore";
import { db } from "@/firebase/clientApp";
import { collection } from "firebase/firestore";
export default function Test(){
const router = useRouter();
const {id} = router.query
const [data, dataLoading, dataError] = useCollection(collection(db, "drafts", id), {})
return(
<div>Hello!</div>
)
}
如您所见,我使用 id 的值来初始化 useCollection 挂钩。但是,id 会发生变化,并且首先是未定义的,然后更改为正确的值。这使得整个事情崩溃了,上面的内容在打字稿中甚至无效。我需要在定义 id 之后初始化 useCollection 钩子,这仅在组件“安装”之后。我尝试将 useCollection(...) 放在 useEffect 中,但它不起作用。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
由于您使用的是 nextjs,因此您可以利用
getServerSideProps为您的组件生成 id 作为初始道具,因此它将始终被定义:export async function getServerSideProps({ params }) { const id = params.id; return { props: { id, }, }; }并且您从组件中收到它作为道具:
export default function Test({id}){ //... }