简体   繁体   English

即使未输入映射循环,React也会在array.map上崩溃

[英]React crashes on array.map even though the map loop isn't being entered

The component ProductCategoriesPicker is accepting an array of categories as categoriesState , which is currently just an empty array [] 组件ProductCategoriesPicker接受一个类别数组作为categoriesState ,当前它只是一个空数组[]

Here's the component: 这是组件:

import React from 'react'

const ProductCategoriesPicker = ({ categoriesState, onCheck }) =>  (
   <div className="product-categories-picker">
       <h5> MY product categories </h5>
       <ul>
           categoriesState.map( (cat, idx)  =>  
               <li>
                   <label>
                       <input 
                           type="checkbox"
                           checked={cat.checked}
                           onChange={onCheck}
                       />
                       {cat.name}
                   </label>
               </li>
           )   
       </ul>
   </div>

)

export default ProductCategoriesPicker

But no matter how I set it up, I get a crash with error message cat is not defined 但是无论我如何设置,都会崩溃,并显示错误消息cat is not defined

First of all, shouldn't map not even enter the loop on an empty array? 首先,映射甚至不应该在空数组上进入循环吗? I've tried several measures to guard against this regardless, and none of them stop the error message: 我尝试了几种措施来防止这种情况的发生,但是没有一种措施可以阻止错误消息:

categoriesState && cateogoriesState.map ... // same error
categoriesState.length > 0 && categoriesState.map ... // same error

And if I try to get a console.log on the cat, nothing at all shows up (not even undefined , which makes me think that indeed, this loop is not being entered. 而且,如果我尝试在cat上获取console.log,则什么也没有显示(甚至undefined ,这使我认为确实没有进入此循环)。

categoriesState.map( (cat, idx) => console.log(cat) && 

This is complete looney toons -- why does the app crash on this error!? 这是完整的looney Toons-为什么应用程序因此错误而崩溃!?

Maybe it's a translation error to SO, but it looks like you have some syntax errors. 也许这是SO的翻译错误,但看起来您有一些语法错误。 I'm fairly sure you need to have your categoriesState.map() inside {} and also to implicitly return the <li> JSX, it needs to be wrapped in () : 我相当确定您需要在{}包含categoriesState.map()并隐式返回<li> JSX,它需要包装在()

<ul>
  {categoriesState.map((cat, idx) => (
    <li>
      <label>
        <input type="checkbox" checked={cat.checked} onChange={onCheck} />
        {cat.name}
      </label>
    </li>
  ))}
</ul>

EDIT: As pointed out in comments, the parentheses are not required for implicit return 编辑:正如注释中指出的那样,隐式返回不需要括号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM