0

Изучая реакт решил сконструировать собственный велосипед(карусель), в процессе подключения обработчиков столкнулся с непонятной ситуацией. Когда нажимаем на кнопки смены слайда в хаотичной очередности слайды переключаются то через один то через два и тд. Подскажите в чем может быть причина. Я думаю, что дело скорее всего в методе setState().

export default class HeroCarousel extends Component {
  
  state = {
    slides: [
      {
        caption: {
          title: 'Slide one',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img.jpg',
      },
      {
        caption: {
          title: 'Slide two',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img1.jpg',
      },
      {
        caption: {
          title: 'Slide three',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img2.jpg',
      },
      {
        caption: {
          title: 'Slide four',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img3.jpg',
      },
      {
        caption: {
          title: 'Slide five',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img4.jpg',
      },
      {
        caption: {
          title: 'Slide six',
          text: `Lorem ipsum dolor sit amet, malorum recteque reprehendunt ea vel. 
          Urbanitas adolescens vim te, per at tritani aperiri. Adhuc invenire convenire his ea.`,
        },
        bg: 'images/content/hero_carousel/slides/img5.jpg',
      },
    ],
    breadcrumbs: [
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img.jpg',
        ariaLabel: 'Example breadcrumb',
      },
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img1.jpg',
        ariaLabel: 'Example breadcrumb',
      },
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img2.jpg',
        ariaLabel: 'Example breadcrumb',
      },
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img3.jpg',
        ariaLabel: 'Example breadcrumb',
      },
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img4.jpg',
        ariaLabel: 'Example breadcrumb',
      },
      {
        previewImage: 'images/content/hero_carousel/breadcrumbs/img5.jpg',
        ariaLabel: 'Example breadcrumb',
      },
    ],
    position: 0,
  }


  goToNextSlide = () => {
    let {
      position,
      slides
    } = this.state;

    if (position === slides.length - 1) {
      position = 0 
    }

    ++position

    return this.setState({
      position: position
    })
  }

  goToPrevSlide = () => {
    let {
      position,
      slides
    } = this.state;

    if (position === 0) {
      position = slides.length - 1 
    }

    --position

    return this.setState({
      position: position
    })
  }

  render() {
    return (
      <div className="carousel" id="hero-carousel">

        {/* Begin control next*/}
        <HeroCarouselControlRight handler={this.goToNextSlide} />
        {/* End control next transform ease-out 450ms */}

        {/* Begin control previous*/}
        <HeroCarouselControlLeft handler={this.goToPrevSlide} />
        {/* End control previous */}

        <div className="carousel__inner" style={{
          transition: 'transform ease-out 450ms', 
          transform: `translateX(-${this.state.position}00%)`
        }}>
          {this.state.slides.map((slide, index) => 
            <HeroCarouselSlide 
              title={slide.caption.title}
              text={slide.caption.text}
              key={index}
              bg={slide.bg}
            />
          )}
        </div>

        <ul className="carousel__thumbs">
          {this.state.breadcrumbs.map((breadcrumb, index) =>
            <HeroCarouselBreadCrumb 
              previewImage={breadcrumb.previewImage}
              dataSlideTo={index}
              ariaLabel={breadcrumb.ariaLabel}
              handler={this.goToSlide}
              key={index}
            />
          )}
        </ul>
      </div>
    )
  }
}

2
  • Если переключаешь соблюдая установленный transition (450ms), адекватно себя ведет ?
    – dev_null
    16 сен 2019 в 15:45
  • Пробовал, дело не в этом. Если в методе render выводит в консоль результаты. То состояния изменяется дважды. 16 сен 2019 в 15:59

1 ответ 1

1

Проблема в том, что вы "мутируете" state. Вместо того, чтобы делать инкремент/декремент значения из стейта, вам нужно возвращать новый стейт. Ниже привожу пример правильной реализации:

  goToNextSlide = () => {
    const {
      position,
      slides
    } = this.state;

    const newPosition = position === slides.length - 1 ? 0 : postion + 1;

    this.setState({
      position: newPosition
    })
  }

Подробнее можете почитать тут.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.