【问题标题】:React Leaflet key warningReact Leaflet 密钥警告
【发布时间】:2020-07-14 08:51:01
【问题描述】:

我有一个遍历数组的函数,获取所有标记数据,然后将它们放入 Map 组件中。 React 不断警告我每个孩子都应该有一把钥匙。 Leaflet 为每个标记生成额外的子级。我无法控制这些额外的孩子。

这是那段代码

{
  this.state.markers.map((content, idx) => (
    <>
      <Marker
        key={`marker-${idx}`}
        icon={content["icon"]}
        position={content["position"]}
      >
        <Popup
          key={`popup-${idx}`}
          closeButton={false}
          className={styles.popup}
        >
          <span>{content["popupText"]}</span>
        </Popup>
      </Marker>
      {content["radius"] && (
        <Circle
          key={`circle-${idx}`}
          center={content["position"]}
          radius={content["radius"]}
          color={content["color"]}
        ></Circle>
      )}
    </>
  ));
}

标记数组由从 firebase 获取数据的函数生成。

firebase.firestore().collection('markers').get().then(async (snap) => {
    snap.forEach((marker) => {
        this.state.markers.push({
            position: marker.data()['position'],
            icon: this.state.icons[marker.data()['icon']][0],
            color: this.state.icons[marker.data()['icon']][1],
            popupText: marker.data()['popupText'],
            radius: marker.data()['radius']
        })
    })
}

【问题讨论】:

    标签: javascript reactjs leaflet


    【解决方案1】:

    React 键需要在映射函数返回的外部节点上,并且不能添加到片段简写中,它需要是一个实际的组件。就 react 而言,嵌套组件中使用的其他键没有任何用途,因此您可以删除它们。

    Lists & Keys

    {
      this.state.markers.map((content, idx) => (
        <Fragment key={/* some unique key value */}> // <-- use key here!
          <Marker
            key={`marker-${idx}`}
            icon={content["icon"]}
            position={content["position"]}
          >
            <Popup
              key={`popup-${idx}`}
              closeButton={false}
              className={styles.popup}
            >
              <span>{content["popupText"]}</span>
            </Popup>
          </Marker>
          {content["radius"] && (
            <Circle
              key={`circle-${idx}`}
              center={content["position"]}
              radius={content["radius"]}
              color={content["color"]}
            />
          )}
        </Fragment>
      ));
    }
    

    注意:也不建议使用数组索引作为键的一部分,除非您知道数组是稳定的,即没有添加/渲染之间的删除和重新排序。

    【讨论】:

    • 哇这个片段。我永远猜不到。谢谢你好心的陌生人
    • @cladestine 是的,这当然是一个很好的陷阱。干杯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2019-10-12
    • 2020-04-15
    相关资源
    最近更新 更多