在 Next 13 中,我有一个带有类别的产品列表。我想将这些类别放入常量中,以便我可以检查产品是否属于一个类别或另一个类别。例如:
if (product.id === CONSTANTS.DRINKS) { //do something with the product if it is from the drinks category }
这些常量将根据外部 API 的请求进行填充。它们必须在整个代码中填写,并将在常见的 javascript 文件和 React 组件中使用。未来13年有办法做到这一点吗?考虑到有些文件在服务器上渲染,而其他使用 RTK 的文件将在客户端渲染。是否有另一种方法可以在整个代码中分布这些常量?
我尝试向 API 发出请求来填写常量,但由于有些文件是在服务器上渲染的,而其他文件是在客户端上渲染的,所以它没有按我的预期工作。它们只能填充一次,所有代码都可以看到该值填充。
参考此:
if (product.id === CONSTANTS.DRINKS) { };
我想你的意思一定是这样的:
if (product.type === CONSTANTS.DRINK_TYPE) {
// check if it's a "drink"
}
/**
* or...
*/
if (constants.DRINKS.includes(product.id)) {
// check if this product ID is apart of a constant array of drinks?
};
我的方法是使用某种与服务器端配合使用的数据模式/模型/表,例如 Prisma 和 Vercel Postgres(如果您使用 vercel 进行部署,强烈推荐)。 虽然您不必专门使用 that 方法来进行数据管理,但同样的概念也适用:
prisma.schema
设置将有利于此目标:
// config / set-up example:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("POSTGRES_PRISMA_URL")
directUrl = env("POSTGRES_URL_NON_POOLING")
}
// the "constant" types
enum ConstantType {
DRINK
FOOD
// ...
}
// the product
model Product {
id String @id @default(uuid())
constantType ConstantType @default(DRINK)
/**
* createdAt DateTime @default(now())
* updatedAt DateTime @default(now())
* ...
*/
}
这将允许每个
product
有一个指定的“类型”,您可以检查它。
import { Product, ConstantType } from "@prisma/client";
const checkProductType = (product: Product) => {
if (product.constantType === ConstantType.DRINK) { };
}
我确实建议与 prisma 和 vercel postgres 集成(个人),但您可以使用您选择使用的任何数据库系统来实现相同的目标。