博客添加分类标签时遇Cannot read properties of null (reading 'map')错误求解决
解决 "Cannot read properties of null (reading 'map')" 错误
这个错误的核心原因是 post.categories 的值为 null,而 null 没有 map 方法,调用时会触发报错。以下是几种可行的解决方法:
方法1:使用可选链操作符(推荐)
在 map 前添加可选链 ?.,当 post.categories 为 null 或 undefined 时,表达式直接返回 undefined,不会执行后续的 map 操作:
<div className="flex flex-col md:flex-row gap-y-2 md:gap-x-2 items-center"> {post.categories?.map((category) => ( <div className="bg-[#f7ab0a] text-center text-black px-3 py-1 rounded-full text-sm font-semibold"> <p>{category.title}</p> </div> ))} </div>
方法2:设置默认空数组
通过逻辑或操作符 ||,在 post.categories 为假值(包括 null)时,用空数组替代,确保 map 能正常执行:
<div className="flex flex-col md:flex-row gap-y-2 md:gap-x-2 items-center"> {(post.categories || []).map((category) => ( <div className="bg-[#f7ab0a] text-center text-black px-3 py-1 rounded-full text-sm font-semibold"> <p>{category.title}</p> </div> ))} </div>
方法3:条件渲染
先判断 post.categories 是否存在且为数组,满足条件再渲染分类标签:
<div className="flex flex-col md:flex-row gap-y-2 md:gap-x-2 items-center"> {Array.isArray(post.categories) && post.categories.map((category) => ( <div className="bg-[#f7ab0a] text-center text-black px-3 py-1 rounded-full text-sm font-semibold"> <p>{category.title}</p> </div> ))} </div>
方法4:从数据源层面优化
如果是从Schema或后端接口获取数据,可以直接设置 categories 的默认值为空数组,避免出现 null 的情况。比如在Schema定义时:
type Post { categories: [Category!]! = [] }
或者在前端获取数据后,统一将 categories 处理成数组格式。
内容的提问来源于stack exchange,提问作者shem dennis
相关产品推荐
相关产品推荐

