【问题标题】:Error: Objects are not valid as a React child (found: object with keys..........)错误:对象作为 React 子对象无效(找到:带键的对象..........)
【发布时间】:2018-01-12 17:56:35
【问题描述】:

我正在尝试遍历对象数组。控制台上 this.state.saveFriendTag 或 this.props.userTags 的值为:

构造函数中的状态是: saveFriendTag:this.props.userTags? this.props.userTags: [],

代码是:

if(this.props.cardData){
  if (this.state.saveFriendTag.length == 1) {
    taggedFriendsBlue =  this.state.saveFriendTag.map((item, index) => {
      console.log(item,"item");
      return (
        <span className="displayedName blue" key={index}>{item.firstname}</span>
      )
    })
  } 

这是回报,taggedFriendsBlue 在渲染中定义:

 <div className="pCard_contentContainer ">
     <textarea id="pcardTextarea" type="text" placeholder="Write Description here..." value={this.state.Description} onChange={this.textareaExpansion.bind(this)}></textarea>
       <If test={this.state.tagDone == true || this.state.saveFriendTag.length>0}>
       <div className="displayNames disp_inliFl">
         <span className="pcard_WithOne">-With</span>
           <div className="disp_inliFl">
               {taggedFriendsBlue}
           </div>
       </div>
    </If>
  </div>

谁能说出这个控制台错误的原因?如何纠正?

【问题讨论】:

  • 你能显示组件的完整渲染方法吗?
  • 如果你试图迭代的集合是一个数组,你不必指定Object.keys

标签: javascript arrays reactjs


【解决方案1】:

看起来问题是您在数组上使用Object.keys。您可以删除它并直接使用.map

此外,您需要为span 指定一个密钥。

&lt;span key={item.id} ... /&gt;

const array = [
  {
    firstName: "test",
    lastName: "test2"
  }
];

console.log(Object.keys(array));

从代码 sn-p 中可以看出,在数组上使用 Object.keys 将导致在 map 函数的每次迭代中传递索引,而不是您想要的对象。

【讨论】:

  • @YogeshDevgun 你在问什么?
  • @YogeshDevgun 不要忘记在 div 中包含 key 属性。
  • 另外,在您刚刚评论的 sn-p 中,item 是一个对象。因此,您应该执行item.firstName 之类的操作来获取值,而不是单独使用对象。
  • @Mathew 抱歉上次发帖! taggedFriendsBlue = this.state.saveFriendTag.map((item, index) =&gt; { console.log(item,"item"); return ( &lt;span className="displayedName blue" key={index}&gt;{item.firstname}&lt;/span&gt; ) }) 这是我现在使用的。我还向 span 添加了键,并删除了直接映射数组的 Object.Keys。但控制台上存在同样的错误
  • 这对你有用还是你仍然看到错误?
猜你喜欢
  • 2021-05-19
  • 2020-02-27
  • 2020-12-28
  • 2020-05-25
  • 2021-03-16
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多