解决方法上面其实以及说到了。只需要找到对象的文件,在 componentWillUnmount
中取消所有的订阅以及异步执行即可。
下面是代码
import React, { Component } from 'react'
import Avatar from '@img/common/avatar.jpeg'
import Stance from '@img/common/stance.png'
class CusImage extends Component {
constructor(props){
super(props)
const defaultImage = props.isAvatar ? Avatar : Stance
this.state = {
src: defaultImage
}
}
componentDidMount(){
const THIS = this
const {imgSrc} = this.props
const img = new Image()
img.src = imgSrc
img.onload = function(){
THIS.setState({
src: imgSrc
})
}
}
// 添加以下代码
componentWillUnmount(){
// 如果有定时器需要清除
// clearTimeout(this.timer)
this.setState = (state, callback) => {
return
}
}
render (){
const {src} = this.state
const {className, alt = "cus-img"} = this.props
return (
<img className={className} src={src} alt={alt}/>
)
}
}
export default CusImage
在 react 16.8 之后的版本中,修改了一下生命周期,移除了一些方法,componentWillMount
就是其中一个。现在如果要使用这个,使用 UNSAFE_componentWillMount
替换。但是不建议使用这个方法