In the app
directory of Next.js 13
, I saw in the official documentation that they have abandoned the old head method in favor of metadata, I think it Can only be used on pages or layouts.
I want to change the title based on the status value, how can I do it? The object in the metadata is outside the component, so I can't reference it.
import type { Metadata } from 'next'; export const metadata: Metadata = { title: 'Home', description: 'Welcome to Next.js', }; export default function Page() { return '...'; }
P粉0256324372023-12-29 09:25:09
If by "state" you mean something similar to "useState", then this is not possible. Because metadata
only applies to server components, and useState
can only be used in client components. Documentation says : p>
For normal pages, you usually know what metadata you want to return, so a metadata
object should be sufficient. If the page is dynamic, there is generateMetadata
:
The following is an example of dynamically setting the title:
// app/products/[id]/page.tsx export async function generateMetadata({ params, searchParams }) { // read route params const id = params.id; // fetch data const product = await fetch(`/api/products/${id}`).then((res) => res.json()); // return a dynamic title return { title: product.title, }; } export default function Page() { return '...'; }