[英]Add a Key to an Array.map
我正在努力了解如何解决警告:
key
不是道具。 尝试访问它会导致返回undefined
。 如果需要在子组件中访问相同的值,则应将其作为其他属性传递。
我在地图函数中添加了“ i”,并将其作为“键”传递给我的孩子。
我不确定“将其作为其他道具传递”是什么意思。 我究竟做错了什么?
{
this.state.accounts.map(function(account, i){
return (
<AccountCard
key={i}
lastTransactions = {account.lastTransactions}
bank={account.bank}
number={account.number}
id={account.id}
/>
)
})
}
在AccountCard组件中,我这样访问密钥/ ID:
<div className=" col-lg-4 col-md-6 col-sm-12 col-xs-12" key={this.props.key}>
不要访问this.props.key
。 关键是React本身。 如果您需要键的值“将其作为其他属性传递” 。 例如:
<AccountCard
key={i}
myKey={i}
lastTransactions = {account.lastTransactions}
bank={account.bank}
number={account.number}
id={account.id}
/>
Key
用于React, myKey
用于您使用this.props.myKey
进行访问。 有关示例,请参阅文档 。
我认为问题不在此片段中(尽管不建议将index作为键,而将account.id
作为键),而是在AccountCard
组件声明中。 我认为您正在尝试执行诸如props.key
类的props.key
。
如果您确实需要在子组件中使用i
,则为此添加另一个道具并在子组件中使用它。
<AccountCard
key={account.id}
i={i}
lastTransactions = {account.lastTransactions}
bank={account.bank}
number={account.number}
id={account.id}
/>
<div className=" col-lg-4 col-md-6 col-sm-12 col-xs-12" key={this.props.i}>
虽然其他答案是正确的,但我想添加一个替代解决方案。
您可以通过将div
包裹在每个AccountCard
上来直接提供密钥,而不是通过任意道具传递密钥。 像这样:
this.state.accounts.map(function(account, i){
return (
<div key={i}>
<AccountCard
lastTransactions = {account.lastTransactions}
bank={account.bank}
number={account.number}
id={account.id}
/>
</div>
)
})
或 ,如果您使用的是React v16.2或更高版本,请使用片段 :
this.state.accounts.map(function(account, i){
return (
<React.Fragment key={i}>
<AccountCard
lastTransactions = {account.lastTransactions}
bank={account.bank}
number={account.number}
id={account.id}
/>
</React.Fragment>
)
})
使用片段不会向DOM中添加任何不必要的元素(就像第一个示例中的div
一样)。 如果愿意,还可以使用<>
和</>
速记语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.