You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在NextJS集成Sanity时,如何定义未知属性的features字段?

解决方案:用数组+嵌套对象实现动态键值对存储

要存储预先未知的键值对(比如bedrooms->2、length->40m这类),你可以用数组类型搭配嵌套对象的方式实现。这种方案不需要预定义具体字段,能自由添加任意键值对,同时在Sanity Studio里的编辑体验也很直观。

修改后的Project Schema代码

在你的project schema的fields数组中插入以下字段(位置可根据需求调整):

export const project: SchemaTypeDefinition = {
  name: "project",
  title: "Project",
  type: "document",
  fields: [
    // 保留原有所有字段...
    {
      name: "price",
      title: "Price",
      type: "number",
      description: "the price of the project in USD",
    },
    // 新增features字段
    {
      name: "features",
      title: "Features",
      type: "array",
      description: "添加项目的自定义特征(如bedrooms、floors等)",
      of: [
        {
          type: "object",
          fields: [
            {
              name: "featureKey",
              title: "特征名称",
              type: "string",
              validation: (Rule) => Rule.required().error("请填写特征名称"),
            },
            {
              name: "featureValue",
              title: "特征值",
              type: "string",
              validation: (Rule) => Rule.required().error("请填写特征值"),
            },
          ],
          // 配置预览,在Studio中更直观查看条目内容
          preview: {
            select: {
              key: "featureKey",
              value: "featureValue",
            },
            prepare(selection) {
              const { key, value } = selection;
              return {
                title: `${key}: ${value}`,
              };
            },
          },
        },
      ],
    },
    // 继续保留原有字段...
    {
      name: "mainImage",
      title: "Main image",
      type: "image",
      description:
        "The face of the project. This image will appear in socials, the shop and more",
      validation: (Rule) => Rule.required(),
    },
    // 其他原有字段...
  ],
};

方案优势

  • 数组类型支持动态添加任意数量的键值对,无需提前定义所有可能的特征字段
  • 嵌套对象结构确保每个条目都有明确的「键」和「值」,数据结构规整,避免混乱
  • 预览配置让你在Sanity Studio的文档列表里直接看到特征内容,编辑更清晰
  • 可通过验证规则确保每个特征的键和值都必填,避免空数据

在Next.js中读取渲染数据

获取Sanity返回的项目数据后,可通过遍历数组渲染特征:

// 假设从Sanity获取的项目数据为projectData
<div className="project-features">
  <h3>项目特征</h3>
  {projectData.features?.map((feature) => (
    <div key={feature.featureKey} className="feature-item">
      <span className="feature-key">{feature.featureKey}:</span>
      <span className="feature-value">{feature.featureValue}</span>
    </div>
  ))}
</div>

可选优化

如果需要支持多种值类型(比如数字或字符串),可以把featureValue改成联合类型:

{
  name: "featureValue",
  title: "特征值",
  type: "union",
  of: [
    { type: "string" },
    { type: "number" },
  ],
  validation: (Rule) => Rule.required().error("请填写特征值"),
}

内容的提问来源于stack exchange,提问作者Amos Machora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 13:55:20