来自 api 的反应图像标题错误可能与正确的索引有关

我的应用程序将 react-images 用于灯箱,将 react-carousel-images 用于轮播。我的 api 有一个标题和图像。我遇到的问题是页脚标题中的标题始终作为所选图像出现,并且在灯箱轮播中不会改变。我认为这与所选图像的索引有关?到目前为止,我的代码是:


问题示例: https ://codesandbox.io/s/react-multi-corousal-issue-72s9o?file=/src/Slider.js


滑块.js


import React, { Component } from "react";

// import "../slider/slider.css";

import "./slider.css";

import Carousel from "react-multi-carousel";

import "react-multi-carousel/lib/styles.css";

import LightBox, { Modal, ModalGateway } from "react-images";


const responsive = {

  superLargeDesktop: {

    breakpoint: { max: 4000, min: 3000 },

    items: 1

  },

  desktop: {

    breakpoint: { max: 3000, min: 1024 },

    items: 1

  },

  tablet: {

    breakpoint: { max: 1024, min: 464 },

    items: 1

  },

  mobile: {

    breakpoint: { max: 464, min: 0 },

    items: 1

  }

};


class Slider extends Component {

  _isMounted = false;


  state = {

    awsApiData: [],

    loading: false,

    //selectedIndex: 0,

    selectedImage: {},

    lightboxIsOpen: false

  };


  componentDidMount() {

    this._isMounted = true;

    console.log("app mounted");

    this.setState({ loading: true });

    /*global fetch */

    fetch("https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/imgApi")

      .then(data => data.json())

      .then(data =>

        // this.setState({ awsApiData: data[0], loading: false }, () =>

        this.setState(

          {

            // awsApiData: data.map(item => ({source: item.download_url })),

            awsApiData: data.map(item => ({

              ...item,

              source: item.image

            })),

            loading: false

          },

          () => console.log(data)

        )

      );

  }

  componentWillUnmount() {

    this._isMounted = false;

  }


  toggleLightbox = (post, selectedIndex) => {

    // this.setState(state => ({

    //   lightboxIsOpen: !state.lightboxIsOpen,

    //   selectedIndex

    // }));

    this.setState(state => ({

      lightboxIsOpen: !state.lightboxIsOpen,

      selectedImage: { title: post.title, index: selectedIndex }

    }));

  };



素胚勾勒不出你
浏览 108回答 1
1回答

撒科打诨

您的标题设置为,但当您的灯箱视图更改时this.state.selectedImage.title,您永远不会更新状态(即 call )。setState()您需要将onViewChange处理程序添加到LightBox组件:<LightBox onViewChange={handleLightBoxViewChange} .../>该处理程序也将接收视图更改的项目的索引。handleLightBoxViewChange呼吁setState更新selectedImage:_handleLightBoxViewChange = (newIndex) => {&nbsp; this.setState(state => ({&nbsp; &nbsp; selectedImage: state.awsApiData[newIndex]&nbsp; }));};如果您不想更新状态,您的页脚组件会接收当前视图,因此您可以像这样更新它:<LightBox&nbsp; components={{&nbsp; &nbsp; FooterCaption: ({currentView}) => <div>{currentView.title}</div>&nbsp; }}&nbsp; //.../>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript