react中遇到的问题

内存泄漏

在这里插入图片描述
在react开发中,我们经常会遇到这种问题,原因是当我们切换组件的时候,组件已经销毁,而ajax请求还在继续,而该组件已经销毁了,react就是报错,认为内存存在泄漏。

解决办法:
封装了一个修饰器函数,对componetWillUnmount和setState改装

function decorator (target) {
    let willUnmount = target.prototype.componentWillUnmount
    // 改装componentWillUnmount钩子函数
    // 在组件销毁的时候,开启一个开关
    target.prototype.componentWillUnmount =function(){
        if(willUnmount) willUnmount.call(this,...arguments);
        // this.unmount = true 说明这个时候组件已经销毁了
        this.unmount = true ;
    }
    let setState = target.prototype.setState;
    target.prototype.setState = function(){
        // 如果组件已经销毁了,那么不进行状态更新
        if(this.unmount) return ;
        setState.call(this,...arguments)
    }
}
export {decorator}

直接渲染从后台传过来的标签

<div dangerouslySetInnerHTML={{__html: "<p>明天会更好!</p>"}} />
 
 
constructor(props) {
		super(props);
		this.state ={
			html:'<p>明天hi更好</p>'
		}
	}
<div dangerouslySetInnerHTML={{__html:this.state.html}}></div>
// oData.info.info  后端返回的数据
<div className={styles.articlePageInfo} dangerouslySetInnerHTML={{__html: `${oData.info.info}`}}>

猜你喜欢

转载自blog.csdn.net/qq_43031907/article/details/84585819