两个 children 在 React 中具有相同的键

Two children with the same key in React

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

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,
      },
    );

  }

有什么建议吗?

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

您传递的是元素而不是索引。如果您的元素相同,则会抛出错误。要传递索引,请使用第二个参数:

.map((element, index)=>

现在,使用 index 会给你不同的密钥。

您可以像这样在地图函数中传递另一个参数:

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

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

这样,您就可以确保您的密钥没有重复。

查看此内容以进一步了解 "key" 相关警告和最佳做法

 function ListItem(props) {
  // Correct! There is no need to specify the key here:
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // Correct! Key should be specified inside the array.
    <ListItem key={number.toString()}
              value={number} />

  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

访问此 link https://reactjs.org/docs/lists-and-keys.html#extracting-components-with-keys 了解更多信息