prevState在componentDidUpdate

时间:2018-09-06 07:38:03

标签: reactjs

道具更改时,我正在使用componentDidUpdate调用某个函数。

问题是我无法将其与prevState进行比较,因为prevState还会显示更新后的状态。因此,我现在不确定如何比较新旧状态。

为什么会这样?

这是代码

componentDidUpdate(prevProps,prevState){
        console.log('prevProps',prevProps);
        console.log('prevstate : ',prevState.urls.length);
        console.log('prevProps : ',prevProps.urls.length);
        console.log('new props in canvas :',this.props.urls.length);

    }

现在,我删除了其余的代码,但是在控制台日志中,我可以看到在prevState和props中url的长度值都相同。 问题在于prevProps显示的值与当前props相同,而prevState显示的值与当前State相同。 所以,我有点困惑如何比较!

你能告诉为什么吗? 这是一个错误吗?

我太早用componentWillReceiveProps尝试过,但是同样出现了同样的问题。

只是为了显示我在何处/何时设置状态

import React, { Component } from 'react';
import { Modal,Button,Icon,Select,Input,Row,Col,Spin} from 'antd';
//import { connect } from 'dva';
import SortableComp from './SortableComp';
import ViewPdfModal from './ViewPdfModal';
import SaveEditedFiles from './SaveEditedFiles';
import TripsForm from '../../routes/Trips/TripsForm';
import {getRequest,postRequest,successNotification,errorNotification} from '../../utils/server-request';
import styles from '../../routes/Trips/EditPdfDetailsModal.less';

export default class CanvasRender extends Component{
    constructor(props){
        super(props);
        this.state={
            urls:this.props.urls,
            urlsOrder:[],
            imgsrc:[],
            viewFileModal:false
        }
        this.canvasRefs = {}
        this.imageRefs = {}
    }

    componentDidMount(){
        console.log('canvas mounted');
        setTimeout(this.pdfConversion(this.props.urls),7000);
       let urls = this.props.urls;
      let urlsOrder = [];
       urls.map((item)=>{
        let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
        if(this.props.type === 'maildoc'||this.props.type==='itinerary'||this.props.item && this.props.item.doctype === 'important' && this.props.item.doctypes && this.props.item.doctypes === 'emaildoc'){
            newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
        }else if(this.props.type === 'agency'){
            newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
        }else if(this.props.type === 'clients'){
            newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
        }
        urlsOrder.push(newItem);
       });
       this.setState({
           urlsOrder

       });
       /*
       if(this.props.getNewOrderEditPdf){
        this.props.getNewOrderEditPdf(urlsOrder);
    }

    this.props.dispatch({
        type: 'global/savePdfOrder',
        payload: urlsOrder
      });
        */
    }

    componentDidUpdate(prevProps,prevState){
        console.log('prevProps',prevProps);
        console.log('prevstate : ',prevState.urls.length);
        console.log('new props in canvas :',this.props.urls.length);
        if(prevState.urls.length!= this.state.urlsOrder.length){
            console.log('new props in canvas in IF :',this.props.urls);
            let urls = this.props.urls;
            let urlsOrder = [];
            urls.map((item)=>{
                let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
                if(this.props.type === 'maildoc'||this.props.type==='itinerary'||this.props.item && this.props.item.doctype === 'important' && this.props.item.doctypes && this.props.item.doctypes === 'emaildoc'){
                    newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
                }else if(this.props.type === 'agency'){
                    newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
                }else if(this.props.type === 'clients'){
                    newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
                }
                urlsOrder.push(newItem);
            });
            this.setState({
                urlsOrder                
            });

            this.pdfConversion(this.props.urls);
        }//end of if
    }//end of didupdate

    // static getDerivedStateFromProps(nextProps, prevState){
    //     console.log('props urls length :',  nextProps.urls.length);
    //     console.log('state urls length :',  prevState.urls.length);
    //     if(nextProps.urls.length!= prevState.urls.length){
    //         console.log('new props in canvas in IF :',nextProps.urls);
    //                 let urls = nextProps.urls;
    //                 let urlsOrder = [];
    //                 urls.map((item)=>{
    //                     let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
    //                     if(nextProps.type === 'maildoc'||nextProps.type==='itinerary'||nextProps.item && nextProps.item.doctype === 'important' && nextProps.doctypes && nextProps.item.doctypes === 'emaildoc'){
    //                         newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
    //                     }else if(nextProps.type === 'agency'){
    //                         newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
    //                     }else if(nextProps.type === 'clients'){
    //                         newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
    //                     }
    //                     urlsOrder.push(newItem);
    //                 });

    //       return { 
    //         urlsOrder,
    //         urls:nextProps.urls
    //     };
    //    }
    //    else return null;
    //  }



    // componentWillReceiveProps(nextProps){
    //     console.log('props urls length :',  nextProps.urls.length);
    //     console.log('state urls length :',  this.state.urls.length);

    //     if(nextProps.urls.length!= this.state.urls.length){
    //         console.log('new props in canvas in IF :',nextProps.urls);
    //         let urls = this.props.urls;
    //         let urlsOrder = [];
    //         urls.map((item)=>{
    //             let newItem = item.replace('http://172.104.60.70/st_old/uploads/tripdoc/split/','');
    //             if(nextProps.type === 'maildoc'||nextProps.type==='itinerary'||nextProps.item && nextProps.item.doctype === 'important' && nextProps.doctypes && nextProps.item.doctypes === 'emaildoc'){
    //                 newItem = item.replace(' http://172.104.60.70/st_old/uploads/maildoc/split','');
    //             }else if(nextProps.type === 'agency'){
    //                 newItem = item.replace('http://172.104.60.70/st_old/uploads/defaultdocs/7/split','');
    //             }else if(nextProps.type === 'clients'){
    //                 newItem = item.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split','');
    //             }
    //             urlsOrder.push(newItem);
    //         });
    //         this.setState({
    //             urlsOrder,
    //             urls:nextProps.urls
    //         });

    //         this.pdfConversion(nextProps.urls);
    //         setTimeout(nextProps.hideLoading(),2000);

    //     }
    //     /*
    //     this.setState({
    //         urls:newUrls
    //     },()=>{
    //         this.pdfConversion(newUrls);
    //     });
    //     */ 
    // }

    pdfLoop = (item,index) => {
        var that = this;
        PDFJS.getDocument(item).then(function getPdfHelloWorld(pdf) {
             //
             // Fetch the first page
             console.log('url is : ',item);
             pdf.getPage(1).then(function getPageHelloWorld(page) {
               var scale = 0.5;
               var viewport = page.getViewport(scale);


                   let cref = 'canvas'+index;
                   let imgref ='img'+index;
                   console.log('cref no : ',cref);
                   console.log('img no : ',imgref);

                   // Prepare canvas using PDF page dimensions
                   //
                   var canvas = that.canvasRefs[cref];
                   //let imagez = that.imageRefs[imgref];
                   var context = canvas.getContext('2d');
                   context.globalcompositeoperation = 'source-over';
                  // context.fillStyle = "#fff";
                  //draw on entire canvas
                  //context.fillRect( 0, 0, canvas.width, canvas.height );
                   canvas.height = viewport.height;
                   canvas.width = viewport.width;

                    //imagez.src = canvas.toDataURL("image/png");
                   //
                   // Render PDF page into canvas context
                   //
                   //page.render({canvasContext: context, viewport: viewport});
                   var task = page.render({canvasContext: context, viewport: viewport})
              task.promise.then(function(){
                //console.log(canvas.toDataURL('image/png'));
                let imgItem = {imgref:canvas.toDataURL('image/png'),page:index+1,rotate:0}

                 let newState = that.state.imgsrc;
                 newState[index] = imgItem;
                 //let newState = that.state.imgsrc.concat(imgItem);
                that.setState({
                    imgsrc:newState
                });
                //imagez.src = canvas.toDataURL('image/png')
              });

             });
           });
       }

    pdfConversion = (urls)=>{
       /* this.props.dispatch({
            type: 'global/savePdfOrder',
            payload: urls
          });*/
          console.log('urls in pdf conversion : ',urls);
        if(window.PDFJS){
            console.log(this.state);
            //let urls = this.props.urls;
            for(var i = 0;i<urls.length;i++){
                let newurl = urls[i];
                //let newurl = 'http://172.104.60.70/st_old/uploads/defaultdocs/7/split/1527165241-42557/1_1527165241-42557.pdf';
                console.log('url : ',newurl);
               this.pdfLoop(newurl,i);
            }

            }
    }

    zoomPdf = (path)=>{
        console.log('path is : ',path);
        let url = path;
        this.setState({
            viewFileModal:true,
            pdfToZoom:url
        });
    }
    closeFileModal = ()=>{
        this.setState({
            viewFileModal:false
        });
    }

    deletePdf = (data,path,index,e)=>{
        console.log('item to delete : ',data);
        console.log('index is : ',index);
        console.log('pdfpath : ',path);
        let newImgSrc = this.state.imgsrc.slice();
        let newOrder = this.state.urlsOrder.slice();
        newOrder.splice(index,1);
        newImgSrc.splice(index,1);
        this.setState({
            imgsrc:newImgSrc,
            urlsOrder:newOrder
        });
        if(this.props.getUrlUpdate){
            this.props.getUrlUpdate(newOrder);
        }else if(this.props.getNewPdfOrder){
            this.props.getNewPdfOrder(newOrder);
        }
        /*
        if(this.props.getNewOrderEditPdf){
            this.props.getNewOrderEditPdf(newOrder);
        }

        this.props.dispatch({
            type: 'global/savePdfOrder',
            payload: newOrder
          });*/
        //also have to remove it from list which is sent to server on submit
        // or another option is to create a list of parts that i send back to server, just before sending
       /* let newUrls = [];
        this.state.urls.map((d)=>{
            if(d !== data){
                newUrls.push(d);
            }
        });
        this.setState({urls:newUrls},this.pdfConversion());
        */
    }


    rotatePdf = (item,index,path,e)=>{
        let newImgSrc = this.state.imgsrc;
        let rotate = '';
        if(newImgSrc[index].rotate<4){
            if((newImgSrc[index].rotate) ===3){
                newImgSrc[index].rotate = 0;
                rotate = 0;
            }else{
                newImgSrc[index].rotate = (newImgSrc[index].rotate)+1;
                rotate = 90*(newImgSrc[index].rotate)
            }
            this.setState({
                imgsrc:newImgSrc
            })

        }
        let urlsOrder = this.state.urlsOrder;
        let newItem = urlsOrder[index].replace('http://172.104.60.70/st_old/uploads/','');
        let file = urlsOrder[index].replace('http://172.104.60.70/st_old/uploads/','').split('/')[3];
        let num = file.split('_')[0];
        let toReplace = '/'+file;
        let filepath = '/'+ newItem.replace(toReplace,'');
        console.log('pdfpath : ',path);

        e.stopPropagation();
        console.log('item data : ',item);
        let url = devUrl + 'trip/retate_pdf/';
        console.log('url is : ',url);
        var formData = new FormData();
        formData.append('filename',this.props.item.name);
        formData.append('filepath',filepath);
        formData.append('angle',rotate);
       // filepath: /tripdoc/split/1528194456-85458
       //angle: 90
       //filename: 2_1527752445-64749.pdf
       postRequest(url,formData, null,response=>{
        console.log('response in data : ',response);

      },error=>console.log(error));    
        // var that = this;
        // fetch(url,{
        //     method: "post" ,
        //     credentials:'include',
        //     body:formData
        //   }).then((response)=>{
        //       return response.json();
        //   }).then((data)=>{
        //       return data;
        //   }).catch((err)=>console.log(err));

    }

    reorderArray = (oldIndex,newIndex,array)=>{
        let elementMoved = array[oldIndex];
        array[oldIndex]=array[newIndex];
        array[newIndex]=elementMoved;
        return array;
    }

    reOrder = (oldIndex,newIndex)=>{
        let newImgSrc = this.state.imgsrc;
        let newOrder = this.state.urlsOrder;
        console.log('array before sorting : ',newOrder)
       newImgSrc= this.reorderArray(oldIndex,newIndex,newImgSrc);
       newOrder = this.reorderArray(oldIndex,newIndex,newOrder)
       console.log('array after sorting : ',newOrder);
       if(this.props.getNewPdfOrder){
           this.props.getNewPdfOrder(newOrder);
       }
       /*
       if(this.props.getNewOrderEditPdf){
           this.props.getNewOrderEditPdf(newOrder);
       }

       this.props.dispatch({
        type: 'global/savePdfOrder',
        payload: newOrder
      });*/
       this.setState({
           imgsrc:newImgSrc,
           urlsOrder:newOrder
       });
    }

    updateCategory = (value) =>{
        this.setState({
        categorySelected:value
        });
    }

    render(){
        let num = this.props.num;
        let canvasDiv = [];
        let imgsDiv = [];
        if(this.state.imgsrc.length>0){
            this.state.imgsrc.map((item,index)=>{
              //let imgz =  <img key={index} src={item.imgref} alt="pdfimg"/>;
              let pdfpath = this.state.urlsOrder[index];
              //let pdfIndex = pdfpath.replace('http://172.104.60.70/st_old/uploads/clientsdoc/split/','').split('/')[1].split('_')[0];
              let pdfIndex = item.page;
              let rotate = '';
              let rotateStyle = null;
              if(item.rotate){
                  rotate = 90*(item.rotate);
                  rotateStyle = {transform:`rotate(${rotate}deg)`};

              }
              //"http://172.104.60.70/st_old/uploads/clientsdoc/split/1529916893-26743/1_1529916878-36442.pdf"
              let imgz = (<div> <div className={styles.pdfButtons} >
                <span>Page No. {pdfIndex}</span>
                 <span className={styles.actIcons}>
                 <Icon onClick={(e)=>this.rotatePdf(item,index,pdfpath,e)} type="reload" /> <Icon onClick={(e)=>this.deletePdf(item,pdfpath,index,e)} type="close-circle-o" />
                 </span> 
                   </div>
                <img className={styles.imgThumb}  style={rotateStyle} src={item.imgref} key={index+100}  alt = "pdfimage"/><br/>
                <span className={styles.zoom} ><Icon onClick={()=>this.zoomPdf(pdfpath)} type="search" /> </span>
               </div>)
              imgsDiv.push(imgz);
            });
        }
        this.props.urls.map((item,index)=>{
            let canv =  <canvas key={index} style={{display:'none'}} ref={(ref) => this.canvasRefs[`canvas${index}`] = ref} > </canvas>;
            canvasDiv.push(canv);

        });

        return(
            <div>
            {canvasDiv.length>0?canvasDiv:''}
            {imgsDiv.length>0 && !this.props.showEditForm &&!this.props.showEmailUploadForm ?  <SortableComp reOrder={this.reOrder} hideLoading={this.props.hideLoading} imgsDiv={imgsDiv}  />  :''}
        {this.props.type && this.props.type==='addDoc'? '' : <div>{this.props.type==='maildoc' &&this.props.whichTab==='itinerary'?
          this.props.showEditForm ||this.props.type === 'maildoc' && this.props.showEmailUploadForm ?  <TripsForm 
            getUpdatedData={this.props.getUpdatedData}
            airlinesCategories={this.props.airlinesCategories}
            updateAirlineCat={this.updateAirlineCat}
            selectedAirlineCat = {this.state.selectedAirlineCat}
            updateSelectedCategory={this.updateCategory} 
            categorySelected={this.state.categorySelected} 
            whichTab={this.props.whichTab}
            // getUpdatedData={this.props.getUpdatedData} 
            closeModal={this.props.closeModal} 
            pdfOrder={this.state.urlsOrder} 
            // onSave={this.onSave} 
             categories={this.props.categories}
             type={this.props.type}
             tripid={this.props.tripid}
            // item={this.props.item}
            />:''
        :this.props.showEditForm && !this.props.uploadEmailDoc || this.props.showEmailUploadForm && this.props.uploadEmailDoc?<SaveEditedFiles
         getUpdatedData = {this.props.getUpdatedData}
         tripid={this.props.tripid}
         whichTab={this.props.whichTab}
        //  impCategories={this.props.impCategories}
         guidesCategories={this.props.guidesCategories}
         librarycategories={this.props.librarycategories}
         getClientDocs = {this.props.getClientDocs?this.props.getClientDocs:''} //from getclientdocs - 
         showSuccessMessage={this.props.showSuccessMessage} //from view client docs
         closeModal={this.props.closeModal}  // editpdf function from view client docs
         hideSplitFiles={this.props.hideSplitFiles}  //from editpdfmodal
         clientid={this.props.clientid}
         type={this.props.type}  // from addclientdocmodal which is getting it from the card we click on
          item={this.props.item}  // it is itemToedit - getting from viewclientdocs
           urlsOrder={this.state.urlsOrder}  //was getting from editpdfmodal but now will get from canvasrender
           categories={this.props.categories} 
           clientCategories={this.props.clientCategories}
           impCategories={this.props.impCategories}  // was getting from editpdfmodal and will still get it from there but pass through a number of components
            />:''}<br/></div>}
            {this.state.viewFileModal?<ViewPdfModal viewFileModal={this.state.viewFileModal} closeModal={this.closeFileModal} filepath={this.state.pdfToZoom}  />:''   }              

            </div>
        )
    }
}

2 个答案:

答案 0 :(得分:0)

您可以大大缩短所有this.props和this.state:

     getUpdatedData = {this.props.getUpdatedData}
     tripid={this.props.tripid}
     whichTab={this.props.whichTab}

进入

     const {getUpdatedData, tripid, whichTab} = this.props

您确定长度应该不同吗? 您有许多setState()调用-可以更早进行修改。显示“画布安装”中的整个日志。

答案 1 :(得分:0)

componentDidUpdate将按原样工作。在componentDidUpdate上检查此演示。

Demo

我猜,问题出在setState时组件(状态或道具)之间的某个地方。

您能否公开代码库或使用最少的代码进行演示,这会有所帮助。 对于参考,请检查以下内容:prevState in componentDidUpdate is the currentState?