Загруженное изображение не отображается в карусели React-Strap - PullRequest
0 голосов
/ 20 сентября 2019

у меня есть один компонент для отображения списка изображений и в этом методе OnfileChange, показанном ниже:

onFileUplod = (body: any) => {
    const response = new ApiHelper().MakeRequestWithBody(
        "SftpImage",
        "PUT",
        body
    );
    response.then((ResponseText: any) => {
        let response = JSON.parse(ResponseText);
        const { curruntImageData } = this.state;
        let index = this.state.sftpImages.findIndex(el => el.imageId === this.state.curruntImageData.imageId);

        this.state.sftpImages[index] = response.data;
        this.getAllSftpImages();
        this.setState({
            activeIndex:index,  
            curruntImageData: curruntImageData,
            showModal:true
        })
    }).catch((error) => {
        this.getAllSftpImages();
        console.log("Error caught in catch", error);
    });
}

И это мой компонент Sftp:

import React, { Component, createRef } from 'react';
import { ISftpImage } from '../../models/SftpImages';

import {
    Modal,
    ModalBody,
    Carousel,
    CarouselControl,
    CarouselItem,
} from 'reactstrap';
import FileSaver from 'file-saver';
import { ApiHelper } from '../../utils/api';


declare var React360: any;

export interface IModalProps {
    curruntImage: ISftpImage;
    Images: ISftpImage[];
    activeIndex: number;
    getAllSftpImages: () => any;
    onFileUplod:(body:any)=>void;
    showModel:boolean
}

export interface IModalState {
    showModal: boolean;
    activeIndex: number,
    curruntImage: ISftpImage,
    loading: boolean,
    actionModal: boolean,
}



class SftpComponent extends Component<IModalProps, IModalState> {
    private refFileUpload = createRef<any>();
    constructor(props: IModalProps) {
        super(props);
        this.state = {
            loading: false,
            showModal: false,
            actionModal: false,
            activeIndex: 0,
            curruntImage: {
                imageId: 0,
                currentUrl: '',
                retouchUrl: '',
                imageName: '',
                statusId: 0,
                createdBy: 0,
                updatedBy: 0,
                updatedDate: '',
                createdDate: '',
                caption: '',
                urlMaxSizeThumbnail: '',
                is360Image: false,
                urlexIfDetail: '',
                comment: '',
                isdownloaded: false,
                isretouched: false
            }
        };
    }


componentDidMount() {
    this.setState({
        activeIndex: this.props.activeIndex,
        curruntImage: this.props.curruntImage,
        // showModal:this.props.showModel
    })
}

handleModalShowClick = (modeltype: string) => {
    if (modeltype == "imagemodel") {
        this.setState({
            showModal: true
        })
    }
    if (modeltype == "upload") {
        this.setState({
            actionModal: true
        })
    }
}
handleModalCloseClick = (modeltype: string) => {
    if (modeltype == "imagemodel") {
        this.setState({
            showModal: false
        })
    }
    if (modeltype == "upload") {
        this.setState({
            actionModal: false
        })
    }
}

next = () => {
    const nextIndex = this.state.activeIndex === this.props.Images.length - 1 ? 0 : this.state.activeIndex + 1;
    const propertyImage = this.props.Images[nextIndex];
    this.setState({
        curruntImage: propertyImage,
        activeIndex: nextIndex,
    })
}
previous = () => {
    const nextIndex = this.state.activeIndex === 0 ? this.props.Images.length - 1 : this.state.activeIndex - 1;
    const propertyImage = this.props.Images[nextIndex];
    this.setState({
        curruntImage: propertyImage,
        activeIndex: nextIndex,

    })
}
handleModalSubmitClick = (action: string) => {
    if (action === "download") {
        this.setState({
            loading: true,
            actionModal: false,
            showModal: true
        })
        let item = this.state.curruntImage;
        let url = item.currentUrl
        let ext = '.jpg';
        let imageId = item.imageId
        return fetch(url, {
            method: 'GET',
            redirect: 'follow',
            referrer: 'no-referrer',
            cache: 'no-cache',
        }
        ).then(this.parseBlob)
            .then((response: Blob) => {

                FileSaver.saveAs(response, imageId + ext)
                let curruntImage = this.state.curruntImage;
                curruntImage.isdownloaded = true
                const res = new ApiHelper().MakeRequest(
                    "SftpImage/" + imageId,
                    "PUT",
                );
                this.setState({
                    curruntImage: curruntImage,
                    loading: false,
                    showModal:true
                })
            })
            .catch((error) => {
                console.log(error);
                this.setState({
                    loading: false
                })
            });
    }
    if (action === "upload") {
        this.refFileUpload.current.click()
    }
}

parseBlob = (response: Response) => {
    return response.blob();
};

onFileChange = (e: any) => {
    this.setState({loading: true });
    let file = e.target.files[0];
    const body = new FormData();
    body.append('ImageId', String(this.state.curruntImage.imageId));
    body.append('RetouchImageFile', file);
    this.props.onFileUplod(body);
    this.setState({loading: false });
}

render() {

    if (this.state.loading) {
        return (
            <div className="jtb_background jtb_page_height">

                <div className="container-fluid  heighvh100">
                    <div className="spinnerwrapper"><i className="fas fa-spinner fa-spin"></i></div>
                </div>

            </div>
        )
    }
    const slides = this.props.Images.map((item: any, index: number) => {
        const url = item.isretouched ? item.retouchUrl : item.currentUrl
        return (

            <CarouselItem
                key={item.imageId}
                className="item"
                tag="div"
            >
                <div className="jtb_carousel_height">
                    <ul className={item.is360Image ? 'jtb_property_big_img360' : 'jtb_property_big_img'}>
                        <li className="slider_img_jtb">
                            {item.is360Image ?
                                <iframe src={"/React360/index.html?url=" + url} height="700px" width="100%" /> :
                                <img src={url} className="img-fluid max_img_height" id="imageSliderTemp" />}
                            <ul className="img_desc_jtb">
                                <li><span> {this.state.activeIndex + 1}</span><span>/</span><span>{this.props.Images.length}</span></li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </CarouselItem>
        );
    });
    const imageDetails = this.state.curruntImage.urlexIfDetail ? JSON.parse(this.state.curruntImage.urlexIfDetail) : {};
    return (
        <React.Fragment>
            <ul className="img_collage" onClick={() => this.handleModalShowClick('imagemodel')}>
                <li className="position-relative" >
                    <img src={this.props.curruntImage.urlMaxSizeThumbnail}
                        alt={this.props.curruntImage.caption} />
                </li>
            </ul>
            <Modal isOpen={this.state.showModal} toggle={() => this.handleModalCloseClick('imagemodel')}
                modalClassName={' propertyslidermodal modal_full_jtb serachresultmodal '}
                contentClassName={'jtb_popup_height sftpmodel'}
                className={'modal-dialog-centered'}
            >
                <ModalBody>
                    <div className="row slidernewweap">
                        <div className="col-lg-12 jtb_popup_close">
                            <button type="button" className="close" onClick={() => this.handleModalCloseClick('imagemodel')}>
                                <img src="/images/close.png" alt="Close" /></button>
                        </div>
                        <div className="col-lg-8" id="slider">
                            <Carousel activeIndex={this.state.activeIndex} next={this.next} previous={this.previous} className="full_thumbnail_slider full-popup-n" tag="div" interval={false} autoPlay={false} slide={true}>
                                {slides}
                                <div className="carousel_nxt_prv_arw">
                                    <CarouselControl direction="prev" directionText="Previous" onClickHandler={this.previous} className="carousel-control left" />
                                    <CarouselControl direction="next" directionText="Next" onClickHandler={this.next}
                                        className="carousel-control right" />
                                </div>
                            </Carousel>
                        </div>

                        <div className="col-lg-4 sideinfo">
                            <ul className="imageinfowrapper">
                                <li className="jtb_img_desc">
                                    <ul className="small_detail">
                                        <li>
                                            <span>Created Date</span>
                                            <label>{new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'numeric', day: 'numeric' }).format(new Date(this.props.curruntImage.createdDate))}</label>
                                        </li>
                                        {
                                            imageDetails && Object.keys(imageDetails).map((key: any, index: number) => (
                                                <li key={index}><span>{key}</span>
                                                    <label>{imageDetails[key]}</label>
                                                </li>
                                            ))
                                        }
                                    </ul>
                                </li>
                            </ul>

                            <div className="rightsideprpfooter">
                                <ul className="jtb_function_btn">
                                    <li>
                                        <button title="Download" onClick={() => this.handleModalSubmitClick('download')}>
                                            <img src="/images/download.png" alt="Download" />
                                        </button>
                                    </li>
                                    <li>
                                        <button
                                            className="file_upload_jtb"
                                            title="Upload"
                                            disabled={this.state.curruntImage.isdownloaded ? false : true}
                                            onClick={() => this.handleModalShowClick('upload')}>

                                            <img src="/images/upload.png" alt="upload" />
                                            <input type="file"
                                                ref={this.refFileUpload}
                                                style={{ display: 'none' }}
                                                onInput={(event) => { this.onFileChange(event) }}
                                                onClick={(event: any) => { event.target.value = null }} />
                                        </button>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </ModalBody>
            </Modal>
            {
                this.state.actionModal ?
                    <Modal isOpen={this.state.actionModal} toggle={() => this.handleModalCloseClick('upload')} modalClassName={'jtb_small_popup '} className={'modal-dialog-centered'}>
                        <div className="modal-content">
                            <div className="modal-body">
                                <div className="action_text_jtb">
                                    <h3>Upload photo?</h3>
                                </div>
                                <div className="action_text">
                                    <p>The picture will be replaced. Are you sure you want to Upload new photo?</p>
                                </div>
                                <ul className="action_btn_jtb">
                                    {
                                        <React.Fragment>
                                            <li><button type="button" className="btn cancl_btn" onClick={() => this.handleModalCloseClick('upload')} >Cancel</button></li>
                                            <li><button type="button" className="btn jtb_red_btn" onClick={() => this.handleModalSubmitClick('upload')}>OK</button></li>
                                        </React.Fragment>
                                    }

                                </ul>
                            </div>
                        </div>
                    </Modal>
                    : ''
            }
        </React.Fragment>

    )


}
}

экспорт по умолчанию SftpComponent;

теперь проблема в том, что когда я нажимаю на кнопку загрузки и выбираю любое изображение, слайдер автоматически закрывается, и загруженное изображение не отображается в списке изображений, мне нужно обновить страницу для этого, я хочу эточто я не хочу закрывать ползунок, и загруженное изображение обновляется на текущем слайде, но оно не влияет должным образом

1 Ответ

0 голосов
/ 20 сентября 2019

Я сталкивался с таким типом ошибки.

Решение: ваш компонент не ожидает загрузки изображения.прежде чем он завершится, он запустит весь процесс, он рендерит дополнительный код. так что вы не получаете свое изображение в изображениях.

Итак.попробуйте добавить асинхронную функцию, которая запускается на сервере и дает правильные результаты.

...