问题详情:
当页面上使用了同一个viewer组件时,打开页面,切换Id获取第二组图片时,点击放大图片出现了以下问题。相关代码如下:
图片组件
import React, { Component } from 'react';
import Proptypes from 'prop-types';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
import './index.less';
/**
* 图片放大组件
*/
class NoteImg extends Component {
componentDidMount() {
const { id } = this.props
const galley = document.getElementById(id);
this.viewer = new Viewer(galley, {
url: 'data-original',
});
}
componentWillUnmount() {
// console.log(this.viewer)
this.viewer && this.viewer.destroy();
}
render() {
const { imgs, id } = this.props;
return (
<div id={id}>
<div className="note-img">
{
imgs.map(img => {
return <div key={img} style={{ height: "180px", width: "190px" }}><img data-original={img} src={img} alt="" /></div>
})
}
</div>
</div>
)
}
}
NoteImg.propTypes = {
imgs: Proptypes.array.isRequired,
id: Proptypes.string.isRequired,
}
export default NoteImg;
css
.note-img {
display: flex;
flex-wrap: wrap;
> div{
width: 190px;
height: 180px;
margin: 5px;
border: 1px solid #ccc;
overflow: hidden;
text-align: center;
>img{
width: 180px;
}
}
}
业务代码
state = {
imgList:[],
Id:0
}
getNotePhoto = (Id) => {
const params = { Id };
API.getImg(params)
.then((res) => {
if (res.code === "200") {
// 图片路径集合
const imgList = res.data.map(el => noteImageUrl + el.imagename);
// this.setState({ imgList : [] }, () => {
this.setState({ imgList });
// });
}
})
}
render(){
const {imgList, Id} = this.state;
return (
<NoteImg imgs={imgList} id={"note" + Id} />
)
}
显示问题截图如下:
react使用的setState时,具有延时性,当我们在没有清空之前的imgList直接赋值时,viewer取值发生错误,导致显示错误。
解决办法
先清空imgList,然后再重新赋值。做法如下:
this.setState({imgList:[],()=>{
this.setState({imgList: list})
}})