我收到一条警告,提示数组中的每个 child 都需要一个键。我以前遇到过这个,我在 Coffeescript 中解决了它:"Each child in an array should have a unique key prop" only on first time render of page
我知道我必须通过 map
传递 key ,这样 map
调用的每个数组都会收到一个唯一的 key 。在 Coffeescript 中,我可以这样做:
component1 = React.createClass({
render: () ->
_.chain(@state.users).map((x) -> <component2 profile={x} key={x.id} />),@).value()
)}
component2 = React.createClass({
render: () ->
return (
<div>Test</div>
<div>Test</div>
)
})
我尝试在 Javascript 中执行此操作,而不是调用新组件,我只是调用同一组件内的另一个函数。我仍然收到警告:
export default class About extends React.Component {
aboutMe(item) {
return (
<div className="col-xs-12">
<div className="about-body">
<p>{item.description}</p>
</div>
</div>
)
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-xs-9">
{_.chain(this.props.about).map(this.aboutMe).value()} # How would I pass in a key in this `map`?
</div>
</div>
</div>
)
}
最佳答案
如果 item
具有可用作键 (demo) 的 ID(或其他属性),您可以执行相同的操作:
aboutMe(item) {
return (
<div className="col-xs-12" key={ item.id }>
<div className="about-body">
<p>{item.description}</p>
</div>
</div>
)
}
关于javascript - 通过 Javascript 中的映射函数传入 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39058234/