react警告:Can only update a mounted or mounting component. This usually means

报这个错归根到底的原因是:试图在页面卸载后操作页面元素,比如以下几种实例:

1.window的几个事件。例如onscroll、ontouchmove等,在某一个页面绑定了事件函数fun,但是当此页面卸载时,事件函数fun还存在,可能fun试图操作被卸载组件的某个元素,因此报错。 解决方式: 在componentWillUnmount函数中,取消掉事件绑定,以onscroll事件为例:

componentWillUnmount(){
    window.onscroll = null
}
复制代码

2.设置了定时器,在页面卸载后,定时器还在操作页面里的元素,例如以下是我编写的一个toast组件:

import React, { Component } from 'react';
import '../styles/Toast.css';
class Toast extends Component {
  constructor(props) {
    super(props);
    this.state = {
        isShow: false,
        tip: '不能为空!'
    };
  }
show = (tip, time = 2500, cb = () => {}) => {
    this.setState({
        isShow: true,
        tip
    })
    setTimeout(() => {
        this.setState({
            isShow: false
        })
        cb()
    }, time)
}
hide = () => {
    this.setState({
        isShow: false
    })
}
componentWillUnmount(){
    this.hide()
}
componentDidMount() {
}
  render() {
    const { isShow, tip } = this.state;
    const { locate } = this.props
    return (
      <div className={ `toast ${ isShow ? 'isShow' : 'hide' } ${ locate=='top' ? 'locateTop' : '' }` }>{tip}</div>
    );
  }
}
export default Toast;

//--------在别的组件调用-----------
//<Toast
//  ref={(e) => { e && (this.toast = e) }}
//  position={'center'}
//  show={show}
///>
复制代码

当我在别的组件里调用:

this.toast.show('注册成功,立即去登录', 3000)//3000是弹出的时间长度
复制代码

在此组件消失之前,我已经跳到别的页面,但是toast在3秒之后会执行消失操作,因为页面卸载,所以操作不到toast,就会报错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值