import React, { Component } from 'react'; import "./imgCom.css" export default class imgCom extends Component { constructor() { super(); this.state = { imgUrl: "", httpImg:"", base64Url:"" } } static getDerivedStateFromProps(props,state){ let {httpImg,imgUrl} = props; if(httpImg&&httpImg!==state.httpImg){ return { httpImg, imgUrl } }else if(imgUrl!==state.imgUrl){ return { imgUrl } } return null } shouldComponentUpdate(nextProps){ if(this.props.imgUrl !== nextProps.imgUrl){ this.count=0; this.getImage(nextProps.imgUrl) return true }else{ if(this.count===0){ this.count ++; return true }else{ return false } } } componentDidMount(){ this.count = 0 if(this.state.httpImg){ this.getImage(this.props.imgUrl) } } getImage(imgUrl) { let {httpImg} = this.state var xhr = new XMLHttpRequest(); xhr.open('POST', httpImg); xhr.setRequestHeader('Content-Type', 'application/json'); var data = { reqInfo: { imgPath: imgUrl }, request: "getImgDataByPath" } xhr.send(JSON.stringify(data)); xhr.onreadystatechange = () =>{ if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 304) { var result = JSON.parse(xhr.responseText) if(result.status === 0){ this.setImgUrl("data:image/png;base64,"+result.resInfo.imgData) }else{ this.setImgUrl(require("./asstes/err.png")) } } } } } setImgUrl(url){ this.setState({ base64Url:url }) } render() { let {base64Url} = this.state return } }