javascript – 使用动态内容实现Swiper Swiper

我正在使用react-id-swiper制作来自Instagram的图像的旋转木马.响应后,Swiper组件似乎没有更新.我认为将我的setState放在componentWillMount中会起作用,但显然不行.当我在Chrome中打开检查器时,它开始工作了吗?

import React, { Component } from 'react'
import Swiper from 'react-id-swiper'
import request from 'superagent'
import './index.css'

const swiperParams = {
  slidesPerView: 5,
  spaceBetween: 0,
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev'
  },
  pagination: {
    el: '.swiper-pagination',
    clickable: true
  },
}

class Carousel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      photos: []
    }
  }

  componentWillMount() {
    this.fetchPhotos();
  }

  fetchPhotos() {
    request
      .get('https://api.instagram.com/v1/users/self/media/recent/?access_token=' + process.env.INSTAGRAM_ACCESS_TOKEN)
      .then((res) => {
        this.setState({
          photos: res.body.data
        })
      })
  }

  render() {
    return (
      <Swiper {...swiperParams}>
        {this.state.photos.map((photo, key) => {
          return (
            <div key={photo.id}>
              <img src={photo.images.standard_resolution.url} alt={photo.caption} />
            </div>
          )
        })}
      </Swiper>
    )
  }
}

export default Carousel

解决方法:

我在react-id-swiper github上找到了this issue,这解决了我的问题.

我只需将shouldSwiperUpdate prop添加到我的Swiper组件中.该组件现在看起来像这样:

<Swiper {...swiperParams} shouldSwiperUpdate>
  ...
</Swiper>

每次重新渲染组件时,这都会更新Swiper.

上一篇:bilibili壁纸站-node爬虫


下一篇:编程语言的编程泛型(截至2021/11/21)