英文:
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 '@/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 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're using `pages` directory, you need to use `useRouter` imported from `next/router`.
```ts
import { useRouter } from "next/router";
If you're using app
directory, you need to use useRouter
imported from next/navigation
.
import { useRouter } from "next/navigation";
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论