我是 nextjs 的新手,正在尝试将 MERN 应用程序转换为 nextjs 15。我使用与 MERN 应用程序相同的后端 api。
我正在尝试在使用“使用客户端”的用户配置文件页面中的 nextjs 15 应用程序中生成动态元数据。
我的基本/[用户名]页面是:
"use client";
import { useParams } from "next/navigation";
import { useAppSelector } from "../redux";
import { useGetProfileByUsernameQuery } from "@/state/api";
const ProfilePage = () => {
const { username } = useParams();
const userInfo = useAppSelector((state) => state.global.userInfo);
const isMyProfile = userInfo && userInfo?.data?.username === username;
const user = useGetProfileByUsernameQuery(username);
const profile = user.status === "fulfilled" ? user.data[0] : "";
return (
<div>
{user.status === "pending" ? (
<h1>Loading...</h1>
) : (
<h1>{`${profile.firstName} ${profile.lastName}`}</h1>
)}
</div>
);
};
export default ProfilePage;
我尝试使用下面的generateMetadata 函数:
export async function generateMetadata({ params }) {
return {
title: `${params.username}'s profile`,
};
}
当我添加这个时,我收到错误
You are attempting to export "generateMetadata" from a component marked with "use client", which is disallowed. Either remove the export, or the "use client" directive.
如果我删除“使用客户端”语句,我将无法获取用户的个人资料。 我从 redux.js 收到错误消息:
You're importing a component that needs `useRef`
您可以参考这个doc
仅服务器组件支持通过generateMetadata 生成的静态和动态元数据。
就你而言
ProfilePage.js
"use client";
import { useParams } from "next/navigation";
import { useAppSelector } from "../redux";
import { useGetProfileByUsernameQuery } from "@/state/api";
const ProfilePage = () => {
const { username } = useParams();
const userInfo = useAppSelector((state) => state.global.userInfo);
const isMyProfile = userInfo && userInfo?.data?.username === username;
const user = useGetProfileByUsernameQuery(username);
const profile = user.status === "fulfilled" ? user.data[0] : "";
return (
<div>
{user.status === "pending" ? (
<h1>Loading...</h1>
) : (
<h1>{`${profile.firstName} ${profile.lastName}`}</h1>
)}
</div>
);
};
export default ProfilePage;
username/page.js
import ProfilePage from './ProfilePage';
export async function generateMetadata({ params }) {
return {
title: `${params.username}'s profile`,
};
}
export default Page(){
return <div><ProfilePage/></div>
}