面试题答案
一键面试在 Next.js 中,可以使用 querystring
模块(Node.js 内置)或者 URLSearchParams
(浏览器原生)来对 id
进行序列化处理。以下是使用 querystring
模块的示例:
- 导入模块:
import querystring from 'querystring';
- 序列化
id
: 假设你在pages/post/[id].js
页面中获取到了id
,并且要跳转到另一个页面,同时传递序列化后的id
。
import { useRouter } from 'next/router';
import querystring from 'querystring';
const PostPage = ({ id }) => {
const router = useRouter();
const handleClick = () => {
const serializedId = querystring.stringify({ id });
router.push(`/another-page?${serializedId}`);
};
return (
<div>
<p>Post ID: {id}</p>
<button onClick={handleClick}>跳转到另一个页面并传递序列化后的id</button>
</div>
);
};
export async function getServerSideProps(context) {
const { id } = context.query;
return {
props: {
id
}
};
}
export default PostPage;
- 在目标页面反序列化
id
: 在another - page.js
页面中获取并反序列化id
。
import { useRouter } from 'next/router';
import querystring from 'querystring';
const AnotherPage = () => {
const router = useRouter();
const { id } = querystring.parse(router.query.id);
return (
<div>
<p>从序列化参数中获取的Post ID: {id}</p>
</div>
);
};
export default AnotherPage;
如果使用 URLSearchParams
(适用于浏览器端):
- 序列化
id
:
import { useRouter } from 'next/router';
const PostPage = ({ id }) => {
const router = useRouter();
const handleClick = () => {
const searchParams = new URLSearchParams();
searchParams.append('id', id);
router.push(`/another-page?${searchParams.toString()}`);
};
return (
<div>
<p>Post ID: {id}</p>
<button onClick={handleClick}>跳转到另一个页面并传递序列化后的id</button>
</div>
);
};
export async function getServerSideProps(context) {
const { id } = context.query;
return {
props: {
id
}
};
}
export default PostPage;
- 在目标页面反序列化
id
:
import { useRouter } from 'next/router';
const AnotherPage = () => {
const router = useRouter();
const searchParams = new URLSearchParams(router.asPath.split('?')[1]);
const id = searchParams.get('id');
return (
<div>
<p>从序列化参数中获取的Post ID: {id}</p>
</div>
);
};
export default AnotherPage;