使用动态内容实现Swiper Swiper

时间:2018-06-11 20:17:58

标签: javascript reactjs instagram-api superagent

我正在使用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

4 个答案:

答案 0 :(得分:4)

在您的对象swiperParamas中包含以下属性

rebuildOnUpdate: true

答案 1 :(得分:1)

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

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

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

每次重新渲染组件时都会更新Swiper。

答案 2 :(得分:1)

尝试添加 observer: true, 赋予

答案 3 :(得分:0)

您需要在渲染器外部的数组中映射:

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

return (
    <Swiper {...swiperParams}>
        {swiperItems}
    </Swiper>
)

这对我有用。

相关问题