我试图通过我的链接 href 传递查询参数,但查询似乎没有通过。单击此处的编辑按钮后,我所通过的查询无处可寻。这是我的代码。要查看的行位于星号内。预先感谢您。
"use client";
import {auth} from "../../../utils/firebase";
import {useAuthState} from "react-firebase-hooks/auth";
import {useRouter} from "next/navigation";
import Message from "../components/message";
import { useEffect, useState } from "react";
import { collection, deleteDoc, doc, onSnapshot, query, where} from "firebase/firestore";
import {db} from "../../../utils/firebase";
import {BsTrash2Fill} from 'react-icons/bs';
import {AiFillEdit} from 'react-icons/ai';
import Link from "next/link";
export default function Dashboard(){
const route = useRouter();
const [user,loading] = useAuthState(auth);
const [posts, setPosts] = useState([]);
//See if user is logged in
const getData = async () => {
if(loading) return;
if (!user) return route.push('/auth/login');
const collectionRef = collection(db, "posts");
const q = query(collectionRef, where("user", "==", user.uid));
const unsubscribe = onSnapshot(q, (snapshot) => {
setPosts(snapshot.docs.map((doc)=> ({...doc.data(), id: doc.id})));
});
return unsubscribe;
}
//Delete Post
const deletePost = async (id) => {
const docRef = doc(db, "posts", id)
await deleteDoc(docRef);
};
//Get users data
useEffect(()=>{
getData();
},[user,loading]);
return(
<div>
<h1>Your Posts</h1>
<div>
{posts.map((post)=>{
return (<Message key ={post.id} {...post} > <div className="flex gap-4">
<button onClick = {()=> deletePost(post.id)}className="text-pink-600 flex items-center justify-center gap-2 py-2 text-sm "><BsTrash2Fill className="text-2xl "/>Delete</button>
**<Link href = {{pathname: "/post", query: {post}}}><button className="text-teal -600 flex items-center justify-center gap-2 py-2 text-sm "><AiFillEdit className="text-2xl "/>Edit</button> </Link>
</div> </Message>
);
})}**
</div>
<button className= "font-medium text-white bg-gray-800 py-2 px-4 my-6 "onClick={()=> auth.signOut()}>Sign Out</button>
</div>
);
};
在 Next.js 中,当您想通过
Link
组件传递查询参数时,query
应该是一个对象,其中键是查询参数名称,值是您想要传递的相应值。在您的代码中,您似乎正在尝试将整个 post
对象作为查询参数传递,如果 post
包含不可序列化的值,这可能会导致问题。
您可以尝试为您的
Link
组件使用以下更新代码:
<Link href={{ pathname: "/post/edit", query: { id: post.id } }}>
<button className="text-teal-600 flex items-center justify-center gap-2 py-2 text-sm">
<AiFillEdit className="text-2xl" /> Edit
</button>
</Link>