【问题标题】:setState() called on an unmounted component [duplicate]在未安装的组件上调用 setState() [重复]
【发布时间】:2017-12-30 06:32:21
【问题描述】:

想法:我想在登录后显示时间并在注销后隐藏它。程序有效,但注销后我收到警告(见图 3)。所以,我想知道:警告会影响应用程序,如果是,如何解决这个问题。

这是 Clock.jsx:

import React from 'react'

export class Clock extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            date: new Date()
        }
    }

    componentDidMount() {
        this.timerID = setInterval(
            () => this.tick(),
            1000
        )
    }    

    componentWillMount() {
        clearInterval(this.timerID)
    }

    tick() {
        this.setState({
            date: new Date()
        })
    }

    render() {
        return (
            <div>
                <hr />
                <p>Current Time: </p>
                <p>{this.state.date.toLocaleTimeString()}.</p>
                <hr />
            </div>
        )
    }
}

在 index.jsx 中调用该组件:

function Logout(props) {
    return (        
        <div>
            <button className="btn btn-danger" onClick={props.onClick}>
                Logout
            </button>
            <Clock />
        </div>
    )
}

图片 1 - 登录:

图 2 - 登录后:

图 3 - 注销后的警告:

【问题讨论】:

  • 当你点击注销时,它会卸载你的&lt;Logout /&gt; 组件吗?

标签: javascript reactjs


【解决方案1】:

尝试在 componentWillUnmount 中调用 clearInterval。这样可以确保当您的 Clock 组件在 DOM 中不可用时,不会调用在 tick 中编写的 setState 方法。

【讨论】:

  • 你能详细说明一下,你为什么在componentWillMount中调用clearInterval。
【解决方案2】:

在 Clock.jsx 中,我输入了 componentWillMount() 而不是 componentWillUnmount() 时出错。

旧代码片段:

componentWillMount() {
    clearInterval(this.timerID)
}

固定:

componentWillUnmount() {
    clearInterval(this.timerID)
}

【讨论】:

    猜你喜欢
    • 2018-11-15
    • 2018-11-19
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2015-12-30
    • 2017-03-10
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多