2016-08-20 33 views
1

我收到有关阵列中每个需要密钥的孩子的警告。我以前就遇到过这一点,我在CoffeeScript的解决了这个问题:"Each child in an array should have a unique key prop" only on first time render of page通过Javascript中的映射函数传递键值

我知道,我必须通过map在关键传球,让每个阵列的map通话将获得一个唯一的密钥。在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> 
     ) 
    } 
+0

那么,什么是' this.aboutMe',它看起来像你正在使用它作为一个函数,你可能想'.map(x => x.aboutMe)'或类似的东西。 – adeneo

回答

2

你做同样的事情,如果item具有可作为钥匙的ID(或其他财产)(demo):

aboutMe(item) { 
    return (
     <div className="col-xs-12" key={ item.id }> 
      <div className="about-body"> 
       <p>{item.description}</p> 
      </div> 
     </div> 
    ) 
} 
+0

我想我应该从调用函数的地方传入密钥。我也尝试在'aboutMe()'中传入一个键,但警告仍然显示。 – patrickhuang94

+0

数组'aboutMe()'创建的每个JSX元素都应该有一个键。你也可以在'aboutMe()'中做。 –

+0

我已经给答案添加了一个演示。看看控制台,看看没有关于'key'的警告。然后删除'key = {item.id}',运行它,然后再次检查控制台。顺便说一句 - 我用'.map()'而不是lodash的地图。 –