两个孩子在React中具有相同的键 [英] Two children with the same key in React

查看:233
本文介绍了两个孩子在React中具有相同的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序正常运行,我的类确实添加了一个新元素,但是我在控制台中看到以下警告!

Application works, my classes really adds a new element but I see below warning in console!

警告:遇到两个具有相同键[object Object]的孩子.键应该是唯一的,以便组件能够保持其唯一性. 跨更新的身份.非唯一键可能会导致孩子 复制和/或省略-该行为不受支持,并且可能 在将来的版本中进行更改. 在div中(由ContentBody创建) 在ContentBody中

Warning: Encountered two children with the same key, [object Object]. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version. in div (created by ContentBody) in ContentBody

这是我的渲染部分:

 return (
            <div ref={this.myRef} style={this.state.myHomeStyle} >
              {this.state.elements.map((i: any) => {
                console.log(">>i>>>>", i);
                return <span style={i.myStyle} key={i} >{i}</span>;
              })}
            </div>
        );

// Where i init 
 public componentDidMount() {

    console.log('componentDidMount');
    this.myDOM  = this.myRef.current;
    this.myDOM.addEventListener(myEventsList.adaptCss, this.adaptCss);

    this.add(12,this.INLINE_TEST_ELE, null);
    this.add(13,this.INLINE_TEST_ELE, null);

  }


// Function add 
private add = (id: number, content: any, event: any ) => {

    let localArr: any[] = [];
    let mEvent: any = null;

    if (event !== undefined) {
      mEvent = event;
    }

    localArr = this.state.elements;
    localArr.push(React.createElement("div", { key: id , onClick : mEvent }, content));

    this.setState(
      {
        elements: localArr,
        visibility : true,
      },
    );

  }

有什么建议吗?

更新: 这是我的入门项目的链接: https://github.com/zlatnaspirala/react-vs-typescript-starter

Update: Here is the link for my starter project: https://github.com/zlatnaspirala/react-vs-typescript-starter

推荐答案

您可以在地图函数中传递另一个参数,如下所示:

You can pass another parameter within your map function like so:

this.state.elements.map((element, index) => {
   return <span style={element.myStyle} key={index} >{element}</span>;
});

Array.prototype.map函数的第二个参数实际上包含该数组中特定元素的当前索引.

The second parameter of the Array.prototype.map function actually contains the current index of the particular element in that array.

这样,您将确保您的密钥没有重复.

This way, you'll be sure that your key is not duplicated.

这篇关于两个孩子在React中具有相同的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆