【问题标题】:React Swiper with Dynamic Content用动态内容反应 Swiper
【发布时间】:2018-11-21 03:46:08
【问题描述】:

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

【问题讨论】:

  • 你能在开发者工具的网络标签中看到发出的请求吗?
  • 感谢您的回复。是的,图像已加载,轮播似乎不知道有多少,并且无法滑动等等。除非我打开似乎触发更新的开发人员工具。

标签: javascript reactjs instagram-api superagent


【解决方案1】:

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

rebuildOnUpdate: true

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 这应该是公认的答案。当 swiper 重新渲染时,这不会改变位置
    【解决方案3】:

    尝试添加 observer: true, 到参数

    【讨论】:

      【解决方案4】:

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

      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>
      )
      

      这对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2015-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多