当我有一个唯一键时,我收到一个唯一键props警告

IT技术 javascript html reactjs reactive-programming
2021-05-05 19:43:59

我是 React 的新手,但我知道唯一键的主要概念。但是,我收到警告。

下面我有一个项目组件:

class Item extends Component {
    state = {}

    render() { 
        return ( 
            <React.Fragment>
                {this.props.item.todo}
            </React.Fragment>
        );
    }
}

下面是我的项目组件以及我有唯一键的地方:

render() { 
    const { items } = this.props;
    return ( 
        items.map(item=>
            <React.Fragment>
                <Item key={item.todo} item={item} />
            </React.Fragment>
        )    
    );
}

有了这一切,我收到了警告!

4个回答

正如其他人所说,您需要key在顶部元素上设置,在您的情况下是Fragment. 但我会改变键值。我不知道你有什么样的数据,item.todo但只是将键设置为值item.todo可能会有问题。我会解释。

一个键应该只在它的兄弟中是唯一的

关于列表和键的 react.org 文档完美地总结了这一点,所以我不会以其他方式解释。下面是这么说的。

数组中使用的键在它们的兄弟中应该是唯一的。但是,它们不需要是全局唯一的。当我们生成两个不同的数组时,我们可以使用相同的键:

(注意:它不需要是有意义的数据)。

密钥应该是稳定的

这意味着,之间呈现的关键不应该改变,所以不要使用Math.random()一些人认为将是很好的使用。

为什么上述很重要?

在您的数据中,如果两个items.todo值相同,则会破坏上述内容。您的密钥不会是唯一的。这可能会导致不必要的重新渲染导致性能问题。

我建议使用具有地图items.todo值的键index这样,如果您确实具有items.todo添加索引的相同值,则会使键唯一。考虑到这一点,我会写下你的片段。

render() { 
  const { items } = this.props;

  return ( 
    items.map((item, index) => (
      <React.Fragment key={item.todo + index}>
        <Item item={item} />
      </React.Fragment>
    ))
  );
}

这里是关于列表和键的 react.org 文档的链接,是关于片段的 react.org 文档的链接两者都提供了示例和有用的信息。它们很好读,我强烈推荐。

我还注意到,您正在使用,React.Fragment但随后您仅使用Component. 你可以做我假设你已经做的事情Component并破坏Fragement. 像下面这样:

import React, { Component, Fragment } from 'react';

所以你的代码片段更干净一些,如下所示:

items.map((item, index) => (
  <Fragment key={item.todo + index}>
    <Item item={item} />
  <Fragment>
))

key正如@Tholle 在答案中所建议的那样,您需要将props保留在顶部元素上。但在这里,我想建议的是不要使用<React.Fragment>

items.map(item=>
   <Item key={item.todo} item={item} />
)

Fragment使用时,你不希望与喜欢的包装来包装元素<div /><p />等等。既然你的<Item />组件,使用Fragment是不必要的。

这是示例,以防您可以使用Fragment

items.map(item=>
   <React.Fragment key={item.todo}>
     <Item item={item} />
     <p>Another Component...</p>
   </React.Fragment>
)

但是很抱歉,如果您使用别名Fragment:<></>不支持keyprops。它应该被明确设置,完全没有props。如果您需要使用,则需要用元素包装它们key

items.map(item=>
   <div key={item.todo}>
     <Item item={item} />
     <p>Another Component...</p>
   </div>
)

这将是无效的:

items.map(item=>
   <key={item.todo}>
     <Item item={item} />
     <p>Another Component...</p>
   </>
)

您需要将keyprops放在顶部元素上,即React.Fragment而不是Item.

items.map(item=>
  <React.Fragment key={item.todo}>
    <Item item={item} />
  </React.Fragment>
)    

给 React.Fragment 钥匙

render() { 
  const { items } = this.props;

  return ( 
    items.map(item =>
      <React.Fragment key={item.todo}>
        <Item item={item} />
      </React.Fragment>
    )
  );
}