Dynamic metadata configuration of Next.js application directory to match status values
P粉713866425
P粉713866425 2023-12-28 22:59:40
0
1
459

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粉713866425
P粉713866425

reply all(1)
P粉025632437

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 '...';
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template