使用Contentful Node模块排序时遭遇Type Error问题求助
解决NextJS14 + Contentful构建时order参数类型错误问题
问题根源
Contentful官方SDK的TypeScript类型定义要求order参数必须是数组类型,而非逗号分隔的字符串。本地开发环境可能因TypeScript严格模式未启用或类型检查宽松,未触发错误;但构建部署时严格的类型校验会检测到类型不匹配,抛出类型错误。
解决方案
将order字段的字符串值改为数组形式,每个排序规则作为数组的独立元素:
调整后的代码示例
await client.getEntries({ content_type: 'reportingMarks', 'fields.mark[match]': search, order: ['sys.contentType.sys.id', 'fields.mark'], // 改为数组格式 skip: skip, limit: limit }).then((response) => { setMarks(response.items); setTotalResults(response.total); setIsPending(false); }).catch((error) => { console.error('Error:', error); });
如果仅需按fields.mark排序,同样改为数组:
order: ['fields.mark']
额外说明
- Contentful SDK支持在排序字段前加
-前缀表示降序,例如['-fields.mark'] - 确保项目的
tsconfig.json中strict模式开启,这能在开发阶段提前发现类似类型问题,避免构建时出错
内容的提问来源于stack exchange,提问作者GrandSlambert
相关产品推荐
相关产品推荐

