面试题答案
一键面试实现思路
- 特定商品重定向:在Next.js的路由系统中,可以使用
getServerSideProps
或getStaticProps
方法,结合商品数据判断商品是否为特定商品,如果是则进行重定向。 - 通用404页面:在Next.js中,可以创建一个
pages/404.js
文件来定义404页面。通过检测请求头中的用户代理(User - Agent)来判断请求来源是移动端还是桌面端,进而展示不同内容。
关键代码片段
特定商品重定向
在 pages/product/[slug].js
文件中:
import { useRouter } from 'next/router';
import React from 'react';
export async function getServerSideProps(context) {
const { slug } = context.query;
// 假设这里有一个判断特定商品的逻辑,例如从数据库查询
const isSpecialProduct = await checkIfSpecialProduct(slug);
if (isSpecialProduct) {
return {
redirect: {
destination: `/special - product/${slug}`,
permanent: false
}
};
}
return {
props: {}
};
}
const ProductPage = () => {
const router = useRouter();
const { slug } = router.query;
return (
<div>
<h1>Product Page: {slug}</h1>
</div>
);
};
export default ProductPage;
通用404页面
在 pages/404.js
文件中:
import React from'react';
const isMobile = () => {
const userAgent = typeof navigator === 'undefined'? '' : navigator.userAgent;
return /Mobi|Android/i.test(userAgent);
};
const NotFoundPage = () => {
const isMobileDevice = isMobile();
return (
<div>
{isMobileDevice? (
<p>Mobile 404 Page: The page you are looking for doesn't exist.</p>
) : (
<p>Desktop 404 Page: The page you are looking for doesn't exist.</p>
)}
</div>
);
};
export default NotFoundPage;
这里假设 checkIfSpecialProduct
函数是一个用于判断商品是否为特定商品的自定义函数,实际应用中需要根据具体的数据来源(如数据库查询)来实现。