react,缺少地图迭代的唯一键

时间:2019-03-19 11:27:40

标签: javascript reactjs iterator

我遇到一个错误,我错过了地图迭代的关键道具。我的地图里面有地图。能帮我

displayData() {
  const { data, index } = this.state;
  let sortedData = data[index].settings.map((item, id) => {
    const { _init_ } = item.settings;
    return _init_.map((message, index) => {
      const { message_content } = message;

      return message_content === undefined ? null : (
        <>
          <div>
            <div key={index} className="settings-message">
              {message_content}
            </div>
          </div>
          <div>yes</div>
        </>
      );
    });
  });
  return sortedData;
}

2 个答案:

答案 0 :(得分:2)

键应位于父div上。

return message_content === undefined ? null : (
  <div key={index}>
    <div className="settings-message">
      {message_content}
    </div>
  </div>
)

答案 1 :(得分:1)

您的顶级组件需要一个唯一的密钥。使用显式片段语法,并将密钥添加到片段

displayData() {
  const { data, index } = this.state;
  let sortedData = data[index].settings.map((item, id) => {
    const { _init_ } = item.settings;
    return _init_.map((message, index) => {
      const { message_content } = message;

      return message_content === undefined ? null : (
        <React.Fragment key={index}>
          <div>
            <div className="settings-message">{message_content}</div>
          </div>
          <div>yes</div>
        </React.Fragment>
      );
    });
  });
  return sortedData;
}

ps。您的div可能会比实际需要多