繁体   English   中英

数组或迭代器中的每个子代都应具有唯一的“键”道具。 反应JS错误

[英]Each child in an array or iterator should have a unique “key” prop. React JS Error

我已经阅读了其他有关此问题的答案,但无法理解。 我真的不确定在这种情况下将密钥插入哪里

const recursivelyMapChildren = (node, index) => {
return (
    node.children.map((child, i) => {
      if (child.text) return child.text
      const tag = child.tag
      return React.createElement(
        tag,
        {
          key: `${tag}-${index}-${i}`,
          className: `text-block-${tag}`,
          ...child.attributes,
        },
        recursivelyMapChildren(child, index + 1)
      )
    })
  )
}

const STTextBlock = ({ data }) => {
const textTag = data.content[0].tag
  return (
    <div className="text-block">
      {
        data.content.map(textBlock =>
          React.createElement(
            textTag,
            {
              className: `${textTag}`,
            },
            recursivelyMapChildren(textBlock)
          )
        )
      }
      <style jsx>{styles}</style>
    </div>
  )
}

任何帮助,将不胜感激!

您需要向初始数组映射添加键,还请参阅我在哪里添加UNIQUE_KEY_NEEDED_HERE_ALSO

const recursivelyMapChildren = (node, index) => {
return (
    node.children.map((child, i) => {
      if (child.text) return child.text
      const tag = child.tag
      return React.createElement(
        tag,
        {
          key: `${tag}-${index}-${i}`,
          className: `text-block-${tag}`,
          ...child.attributes,
        },
        recursivelyMapChildren(child, index + 1)
      )
    })
  )
}

const STTextBlock = ({ data }) => {
const textTag = data.content[0].tag
  return (
    <div className="text-block">
      {
        data.content.map(textBlock =>
          React.createElement(
            textTag,
            {
              key: `UNIQUE_KEY_NEEDED_HERE_ALSO`
              className: `${textTag}`,
            },
            recursivelyMapChildren(textBlock)
          )
        )
      }
      <style jsx>{styles}</style>
    </div>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM