Next.js 13:如何在图像生成后自动重定向?

huangapple go评论90阅读模式
英文:

Next.js 13: How to Automatically Redirect After Image Generation?

问题

以下是您要翻译的代码部分:

I'm working on a Next.js 13 project and have implemented a functionality that allows users to generate images based on their input. The image generation process is handled by the generateImage function, and it successfully generates the image and stores it in the image state.

However, I'm facing an issue when trying to automatically redirect the user to a new page (/display-image) immediately after the image is generated. I want users to be able to view the generated image without having to manually trigger the navigation.

I have tried using the redirect function from next/navigation to perform the navigation, but I encountered the error "NextRouter was not mounted."

Here's the code block for the implementation:

import { PageWrapper } from '@/components/Page-Wrapper';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import React, { useEffect, useState } from 'react';

export default function Page() {
  const [searchVal, setSearchVal] = useState('');
  const [loading, setLoading] = useState(false);
  const [image, setImage] = useState('');

  async function generateImage(): Promise<any> {
    setLoading(true);
    const response = await fetch(`/api/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt: `${searchVal}`,
      }),
    });
    const data = await response.json();
    setImage(data.url);
    setSearchVal('');
    setLoading(false);
  }

  const router = useRouter();

  useEffect(() => {
    if (image) {
      // Redirect to the new page after generating the image
      router.push(`/display-image?image=${encodeURIComponent(image)}`);
    }
  }, [image, router]);

  return (
    <PageWrapper>
      <div>
        <main className='py-40 px-8 md:px-12 lg:px-24 flex flex-col items-center justify-center'>
          <h1 className='text-center text-5xl md:text-6xl lg:text-7xl font-bold tracking-tight mb-4'>
            Type Your Prompt
          </h1>
          
          <Input
            value={searchVal}
            type='text'
            onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
              setSearchVal(event.target.value)
            }
            className='max-w-md shadow focus:ring-zinc-500'
            placeholder='Enter Name Here...'
          />

          <button
            onClick={() => generateImage()}
            className={cn(
              buttonVariants({ variant: 'default' }),
              'flex items-center justify-center py-3 px-6 mt-6 '
            )}
            disabled={loading}
          >
            {loading ? 'Loading...' : 'Create Your Image'}
          </button>

          {image && (
            <div className='mt-8'>
              <Image
                className='w-64 h-64 object-cover rounded-md shadow-lg'
                src={image}
                alt='AI Generated'
                width={500}
                height={500}
              />
            </div>
          )}
        </main>
      </div>
    </PageWrapper>
  );
}

希望这有所帮助!

英文:

I'm working on a Next.js 13 project and have implemented a functionality that allows users to generate images based on their input. The image generation process is handled by the generateImage function, and it successfully generates the image and stores it in the image state.

However, I'm facing an issue when trying to automatically redirect the user to a new page (/display-image) immediately after the image is generated. I want users to be able to view the generated image without having to manually trigger the navigation.

I have tried using the redirect function from next/navigation to perform the navigation, but I encountered the error "NextRouter was not mounted."

Here's the code block for the implementation:

import { PageWrapper } from &#39;@/components/Page-Wrapper&#39;;
import Image from &#39;next/image&#39;;
import { useRouter } from &#39;next/navigation&#39;;
import React, { useEffect, useState } from &#39;react&#39;;
export default function Page() {
const [searchVal, setSearchVal] = useState(&#39;&#39;);
const [loading, setLoading] = useState(false);
const [image, setImage] = useState(&#39;&#39;);
async function generateImage(): Promise&lt;any&gt; {
setLoading(true);
const response = await fetch(`/api/generate`, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
},
body: JSON.stringify({
prompt: `${searchVal}`,
}),
});
const data = await response.json();
setImage(data.url);
setSearchVal(&#39;&#39;);
setLoading(false);
}
const router = useRouter();
useEffect(() =&gt; {
if (image) {
// Redirect to the new page after generating the image
router.push(`/display-image?image=${encodeURIComponent(image)}`);
}
}, [image, router]);
return (
&lt;PageWrapper&gt;
&lt;div&gt;
&lt;main className=&#39;py-40 px-8 md:px-12 lg:px-24 flex flex-col items-center justify-center&#39;&gt;
&lt;h1 className=&#39;text-center text-5xl md:text-6xl lg:text-7xl font-bold tracking-tight mb-4&#39;&gt;
Type Your Prompt
&lt;/h1&gt;
&lt;Input
value={searchVal}
type=&#39;text&#39;
onChange={(event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt;
setSearchVal(event.target.value)
}
className=&#39;max-w-md shadow focus:ring-zinc-500&#39;
placeholder=&#39;Enter Name Here...&#39;
/&gt;
&lt;button
onClick={() =&gt; generateImage()}
className={cn(
buttonVariants({ variant: &#39;default&#39; }),
&#39;flex items-center justify-center py-3 px-6 mt-6 &#39;
)}
disabled={loading}
&gt;
{loading ? &#39;Loading...&#39; : &#39;Create Your Image&#39;}
&lt;/button&gt;
{image &amp;&amp; (
&lt;div className=&#39;mt-8&#39;&gt;
&lt;Image
className=&#39;w-64 h-64 object-cover rounded-md shadow-lg&#39;
src={image}
alt=&#39;AI Generated&#39;
width={500}
height={500}
/&gt;
&lt;/div&gt;
)}
&lt;/main&gt;
&lt;/div&gt;
&lt;/PageWrapper&gt;
);
}

I suspect that the issue might be related to how Next.js 13 handles routing and page transitions. I'm seeking guidance on how to properly implement the automatic redirection to the /display-image page after the image is successfully generated in Next.js 13. Any help would be greatly appreciated. Thank you!

答案1

得分: 1

如果你正在使用 `pages` 目录,你需要使用从 `next/router` 导入的 `useRouter`

```ts
import { useRouter } from "next/router";

如果你正在使用 app 目录,你需要使用从 next/navigation 导入的 useRouter

import { useRouter } from "next/navigation";

考虑到你提供的代码示例,你正在使用 pages 目录。请尝试从 next/router 导入 useRouter

请参考文档:https://nextjs.org/docs/messages/next-router-not-mounted


<details>
<summary>英文:</summary>
If you&#39;re using `pages` directory, you need to use `useRouter` imported from `next/router`.
```ts
import { useRouter } from &quot;next/router&quot;;

If you're using app directory, you need to use useRouter imported from next/navigation.

import { useRouter } from &quot;next/navigation&quot;;

Considering the code sample you provided, you're using pages directory. Please try to import useRouter from next/router.

Please refer to the documentation: https://nextjs.org/docs/messages/next-router-not-mounted

huangapple
  • 本文由 发表于 2023年7月28日 04:47:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定