React Invariant Violation:对象作为React子对象无效

时间:2017-06-08 10:59:58

标签: javascript reactjs jsx

  

未捕获(在承诺中)错误:对象作为React子对象无效。

labelList是一个对象数组。我在下面添加了一些示例数据。我试图映射这些对象,以便我可以生成每个对象数据的单独行。我尝试过多个事情,例如Object.keys(labelItem).map ......但是错误仍未解决。

<tbody>
  {
    this.state.labelList.map((labelItem,index)=>{
      return (
        <tr key={ index }>
          <td>{labelItem.label}</td>
        </tr>
        )
    })
  }
</tbody>

数据:

labelList: [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]

1 个答案:

答案 0 :(得分:1)

您的代码可以正常工作,如下面的JS小提琴所示。首先检查this.state.labelList的值,它可能不是您的想法。

var labelList = [
  {
    "label": "Title",
    "translation": "Titre"
  },
  {
    "label": "First Name",
    "translation": "Prenom"
  },
  {
    "label": "Last Name",
    "translation": "Nom"
  },
  {
    "label": "Marital Status",
    "translation": "Etat civil"
  },
  {
    "label": "SSN",
    "translation": ""
  },
  {
    "label": "Birth Date",
    "translation": "Date De Naissance"
  }
]

var Hello = React.createClass({
  render: function() {
    return <tbody>
        {
          labelList.map((labelItem,index)=>{
            return (
              <tr key={ index }>
                <td>{labelItem.label}</td>
              </tr>
              )
          })
        }
      </tbody>
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>