2

我正在为 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>

我如何映射这些设置以给他们一个密钥?

4

2 回答 2

3

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

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

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

肮脏的解决方案:

...
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>
   )
}
于 2016-06-09T07:13:27.653 回答
1

为了让 diff 算法在比较 Virtual DOM 时正常工作,react 需要所有列表项都有唯一的键,以便它可以唯一地识别和区分每个组件。解决方案是将列表的索引作为键传递,如上面@noa-dev 所述:

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

  <Slider {...settings}>
     {Cars}
  </Slider>
}
于 2016-06-09T07:19:29.810 回答