每个数组都需要React JS中的唯一键

时间:2016-06-09 06:59:48

标签: reactjs react-slick

我正在为React JS使用React-Slick滑块组件,但我收到一个警告,每个阵列都必须有一个唯一的密钥。

我在滑块组件的设置中有一个数组。设置为:

const settings = {
        dots: false,
        arrows: false,
        autoplay: true,
        autoplaySpeed: 4000,
        responsive: [
            {breakpoint: 310, settings: {slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 468, settings: {slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 750, settings: {slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 800, settings: {slidesToShow: 2, slidesToScroll: 1, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 1200, settings: {slidesToShow: 3, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 1800, settings: {slidesToShow: 4, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 2600, settings: {slidesToShow: 5, slidesToScroll: 2, autoplay: true, autoplaySpeed: 4000}},
            {breakpoint: 100000, settings: 'unslick'}
        ]
    };

我使用这些设置的滑块组件是:

<Slider {...settings}>
      {this.cars()}
</Slider>

如何通过这些设置进行映射以为其提供密钥?

2 个答案:

答案 0 :(得分:2)

我认为这是您可能需要的:

...
render(){
   var Cars = settings.responsive.map.function(car, index){
      return(<div key={index}>YOUR CONTENT</div>);
   }
   return(
    <Slider {...settings}>
        {Cars}
    </Slider>
   )
}

我想补充一点,map函数的第二个参数可以用作一个唯一的索引,它完全适合所请求的键响应属性

肮脏的解决方案:

...
render(){
   var counter = 0;
   var Cars = settings.responsive.map.function(car, index){
      counter++;
      return(<div key={counter}>YOUR CONTENT</div>);
   }
   return(
    <Slider {...settings}>
        {Cars}
    </Slider>
   )
}

答案 1 :(得分:1)

为了使diff-algorithm在比较Virtual DOM时正常工作,react需要所有列表项具有唯一键,以便它可以唯一地识别和区分每个组件。对此的解决方案是将列表的索引作为密钥传递,如@ noa-dev上面所解释的那样:

render(){
  var Cars = this.cars().map(car, index){
    return(<div key={index}>{car}</div>);
  }

  <Slider {...settings}>
     {Cars}
  </Slider>
}