前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >react项目报错集锦

react项目报错集锦

作者头像
踏浪
发布2020-02-11 12:15:21
9490
发布2020-02-11 12:15:21
举报
文章被收录于专栏:踏浪的文章

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

错误截图
错误截图

解决方案

解决方法上面其实以及说到了。只需要找到对象的文件,在 componentWillUnmount 中取消所有的订阅以及异步执行即可。

下面是代码

代码语言:javascript
复制
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-dom.development.js:12427 Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

错误截图
错误截图

解决方案

在 react 16.8 之后的版本中,修改了一下生命周期,移除了一些方法,componentWillMount就是其中一个。现在如果要使用这个,使用 UNSAFE_componentWillMount 替换。但是不建议使用这个方法

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-01-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    • 解决方案
    • react-dom.development.js:12427 Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.
      • 解决方案
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档