【问题标题】:React+Bootstrap complaining about childs not having unique keys, but they all doReact+Bootstrap 抱怨孩子没有唯一键,但他们都有
【发布时间】:2020-07-19 15:48:30
【问题描述】:

我使用 uuid 为我的所有组件提供唯一键,因为我使用 map 生成其中的 90%(我的大部分 UI 是自动生成的)。但是,React 一直抱怨列表的某些子项没有唯一键。我还使用Bootstrap Row 和 Col 组件来订购我的 UI。

当我使用 React Developer 工具检查我的组件时,我可以看到每个组件都有一个唯一的键。

我给键的方法是,我给组件和同一组件的内部元素一个键。

这是我的组件树的一些屏幕截图以及 React 抱怨的确切组件:

http://prntscr.com/tkox62 http://prntscr.com/tkoxb6 http://prntscr.com/tkoxf9

如您所见,每个组件都有一个唯一的键。

错误: http://prntscr.com/tkoxpp

Row 和 Col 是引导组件。

RowInCard 组件:

export default function RowInCard({ elements, toggleRNumpad }) {
  return (
    <>
      <Row key={uuid()} className="card-row">
        {elements &&
          elements.map((element) => {
            // elements in card row
            return (
              <>
                {element.typeOfElement === "TextField" && (
                  <TextField
                    key={uuid()}
                    text={element.text}
                  ></TextField>
                )}
                {element.typeOfElement === "Button" && (
                  <Button
                    key={uuid()}
                    ID={element.ID}
                  ></Button>
                )}
              </>
            );
          })}
      </Row>
    </>
  );
}

按钮:

export default function Button({ ID }) {
  return (
    <Col
      key={uuid()}
    >
      {ID}
    </Col>
  );
}

文本字段:

export default function TextField({ text }) {

  return (
    <Col
      key={uuid()}
      className="text-field card-element"
    >
      {text}
    </Col>
  );
}

【问题讨论】:

    标签: reactjs react-bootstrap


    【解决方案1】:

    一般来说,只有循环渲染的元素才需要key 属性。您的 ButtonTextField 组件不需要密钥。但是,循环内的片段会:

          // No `key` here, it's not in a loop
          <Row className="card-row">
            {elements &&
              elements.map((element, index) => {
                return (
                  // In a loop here, need a `key`
                  <React.Fragment key={index}>
                    {element.typeOfElement === "TextField" && (
                      <TextField
                        // No key here, its parent is not a loop
                        text={element.text}
                      ></TextField>
                    )}
                    {element.typeOfElement === "Button" && (
                      <Button
                        // No key here, its parent is not a loop
                        ID={element.ID}
                      ></Button>
                    )}
                  </React.Fragment>
                );
              })}
          </Row>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 2020-01-24
      相关资源
      最近更新 更多