当用户导航时,我正试图将id
发送到下一页。
我有一个主页,在那里我获取一个数据数组,并使用.map
在一种基于卡的UI中显示它。
现在,当用户单击该卡时,他们将被导航到下一页,显示该卡的详细信息。
假设主页在这里-localhost:3000
用户点击id为234
的卡片
它们将导航到下一页,如下所示:
下一页为-localhost:3000/user/234
现在,我想在这里显示关于id为234的卡的信息。FOr,我确实需要发出一个提取请求,作为这样的提取(https://userdatabase/234
(
上面的234
当然是一个动态id,我如何让这个fetch
请求知道每次点击新卡时都要更改这个id?或者换句话说,How this page"知道";卡的id?
现在,我使用一种变通方法:
- 当用户在第二个页面时,URL将如下
localhost:3000/user/386
- 使用
useRouter
在NextJS中获取此id,如下所示:
import {useRouter} from 'next/router'
`const router = useRouter()`
fetch(`localhost:3000/user/${router?.query?.user})
我知道从URL中获取id并进行新的请求根本不理想,这会导致第二个页面上出现过时的缓存问题。
如何以更好的方式解决此问题?
非常感谢您的阅读。
您需要创建一个动态路由:Next.js Docs
为您的案例制作一个文件pages/user/[id].js
1.客户端
使用以下代码段访问id:
import { useRouter } from 'next/router'
const Component = () => {
const router = useRouter()
const { id } = router.query
return <p>{id}</p>
}
export default Component
2.服务器端
你可以使用它的任何数据提取功能
SSR代码段:
export async function getServerSideProps({ params }) {
const { id } = params
// fetch data from database with id
return {
props: {}, // will be passed to the page component as props
}
}
更多关于传递给数据提取函数的内容,如上下文:上下文参数
将id
添加到useEffect()
的依赖项数组中。大致如下:
import { useState, useEffect } from "react";
import { useRouter } from 'next/router';
function Page() {
const router = useRouter();
const [page, changePage] = useState();
// `query` can only be fully parsed client-side
// so `isReady` flag is needed
const { query, isReady } = router;
const { id } = query;
// also need to parse the query value to undefined or string
const parsedID = id === undefined
? undefined
: Array.isArray(id)
? id[0]
: id;
useEffect(() => {
// refuse to run the effect if query is not ready
// or ID is undefined
if (!isReady || !parsedID ) {
return;
}
// this looks ugly
// but pure promise syntax is even uglier
// and `useEffect()` doesn't accept async functions
(async () => {
// errors are assumed to be handled in the `_app` component
// so no error-handling logic here
const response = await fetch(`localhost:3000/user/${parsedID}`);
const newPage = await response.json();
changePage(newPage);
})()
}, [isReady, parsedID]);
return (
<>
{!page
// show loading placeholder until the page is fetched
? <div>Loading...</div>
// pass the `page` value to whatever component you need
: ...
}
</>
)
}
export default Page;