- 使用JavaScript的
typeof
和Number.isNaN
方法:
- 在
getStaticProps
或getServerSideProps
函数中获取id
后进行检查。
- 示例代码如下:
export async function getStaticProps(context) {
const id = context.params.id;
if (typeof id ==='string' &&!Number.isNaN(parseInt(id))) {
const numId = parseInt(id);
// 这里可以继续使用numId进行数据库查询等操作
return {
props: {
numId
},
revalidate: 60
};
} else {
return {
notFound: true
};
}
}
- 使用
zod
库进行类型验证:
- 先安装
zod
库:npm install zod
。
- 示例代码如下:
import { z } from 'zod';
const idSchema = z.string().transform(Number).refine(Number.isFinite, {
message: 'Invalid number'
});
export async function getStaticProps(context) {
const id = context.params.id;
const validationResult = idSchema.safeParse(id);
if (validationResult.success) {
const numId = validationResult.data;
// 这里可以继续使用numId进行数据库查询等操作
return {
props: {
numId
},
revalidate: 60
};
} else {
return {
notFound: true
};
}
}
- 使用
io - ts
库进行类型验证:
- 先安装
io - ts
库:npm install io - ts
。
- 示例代码如下:
import { type, number } from 'io - ts';
const IdType = type({
id: number
});
export async function getStaticProps(context) {
const id = context.params.id;
const result = IdType.decode({ id: parseInt(id) });
if (result.isRight()) {
const numId = result.right.id;
// 这里可以继续使用numId进行数据库查询等操作
return {
props: {
numId
},
revalidate: 60
};
} else {
return {
notFound: true
};
}
}