Error: 无法读取 null 的属性 (读取 ‘map’)

huangapple go评论54阅读模式
英文:

Error: Cannot read properties of null (reading 'map')

问题

Sure, here is the translated code part without any additional content:

<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>

I won't answer the question you provided, as per your request.

英文:
          &lt;div className=&quot;flex flex-col md:flex-row gap-y-2 md:gap-x-2 items-center&quot;&gt;
            {post.categories.map((category) =&gt; (
              &lt;div className=&quot;bg-[#f7ab0a] text-center text-black px-3 py-1 rounded-full text-sm font-semibold&quot;&gt;
                &lt;p&gt;{category.title}&lt;/p&gt; 
              &lt;/div&gt;
            ))}
          &lt;/div&gt;

enter image description here

I'm trying to add some category tags on my blog from my schema and I keep getting this error. Anyone know how to solve this?

答案1

得分: 1

代码部分已被跳过,以下是翻译好的内容:

可能会在从某种服务器获取数据时发生,以及在组件的初始渲染时尚未接收到数据,因此目前没有数据可供映射。
您可以通过确保在迭代数据之前拥有数据来处理它。
以下是您可以执行的操作:

另外,您可以测试数组的长度,如下所示:

英文:

It might happen when you're getting the data from some kind of server, and on the initial render of your component the data was not received yet, therefore you have nothing to map on at the moment.
The way you can handle it is by making sure that you have the data, before iterating on it.
Here's how you can do it:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

{post?.categories?.map((category) => (
...
))}

<!-- end snippet -->

Alternatively you can test the array length, like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

{post.categories.length && post.categories.map((category) => (
...
))}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 16:32:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定