Payload CMS v2:如何将全局默认值自动设为字段描述?
Payload CMS v2:将全局字符串作为字段description显示的实现问题
我接手了一个Payload CMS v2项目,需求是把存储在全局字符串里的defaultValue直接显示为字段的description,这样用户不用跳转至全局字符串页面就能查看默认内容。
初始组件代码
export const CardInstructionTitle: Field = { type: "row", fields: [ { name: "title", type: "group", fields: [ { name: "default", type: "checkbox", label: "Use Default Instruction", defaultValue: true, admin: { description: `The default value is: ${defaultValue} (it would be great if this worked) `, }, }, { name: "text", type: "text", admin: { components: { Field: Component, }, }, localized: true, }, ], }, ], };
多Block复用的传参方式
因为CardInstructionTitle会被多个Block类型使用,我通过传入Block名称来区分:
export const SelectThePairsCard: Block = { slug: "selectThePairs", interfaceName: "SelectThePairsFields", fields: [ CardInstructionTitle("selectThePairs"), { name: "wordPairs", type: "array", fields: [ { type: "row", fields: [ { name: "firstWord", type: "text", }, { name: "secondWord", type: "text", }, ], }, ], }, ], };
获取全局默认值的函数
通过传入的Block名称调用接口获取对应的全局字符串:
const getDefaultValue = async (defaultTitle) => { let locale = "fr" try { const response = await fetch(`/payload/api/globals/cardInstructionTitles?locale=${locale}`); if (!response.ok) { throw new Error(`Failed to fetch: ${response.statusText}`); } const data = await response.json(); const value = data[defaultTitle]; if (typeof value !== 'string') { throw new Error(`Invalid default value for ${defaultTitle}`); } return value; } catch (error) { console.error(`Error fetching default value: ${error.message}`); return `Error fetching value for ${defaultTitle}`; } };
异步改造后的组件
我把CardInstructionTitle改成异步函数,尝试将获取到的默认值赋值给description:
export const CardInstructionTitle = async (parentName: string): Promise<Field> => { let defaultTitle = await getDefaultValue(parentName) return { type: "row", fields: [ { name: "title", type: "group", fields: [ { name: "default", type: "checkbox", label: "Use Default Instruction", defaultValue: true, admin: { description: defaultTitle, } }, { name: "text", type: "text", admin: { components: { Field: Component, }, }, localized: true, }, ], }, ], } };
遇到的错误
但description字段不接受异步值,持续收到类型错误:
The types of 'admin.description' are incompatible between these types. Type 'Promise<string>' is not assignable to type 'Description | undefined'. Type 'Promise<string>' is not assignable to type 'Record<string, string>'. Index signature for type 'string' is missing in type 'Promise<string>'.
求助问题
有没有更好的实现方式?逻辑上defaultValue应该是可以直接获取到的,但怎么把它正确赋值给description?或者是不是应该换个方案,比如创建一个仅显示defaultValues的自定义组件?我是Payload和TypeScript新手,麻烦帮忙解答。
编辑补充:已经将CardInstructionTitle和getDefaultValue更新为异步,使用的是Payload 2版本。
内容的提问来源于stack exchange,提问作者xpress
相关产品推荐
相关产品推荐

