繁体   English   中英

状态未在componentDidMount中更新

[英]State not being updated in componentDidMount

我正在尝试在React中建立一个倒数计时器。 我的理解是componentDidMount将在render之后立即被调用,因此我可以使用它在延迟一秒钟后使用当前时间调用setState 像这样:

componentDidMount() {
    setTimeout(this.setState({ now: this.getTime() }), 1000)
}

但是,在调用componentDidMount (我通过console.log进行了检查),状态没有更新。 如何获取componentDidMount来更新状态,从而用新的时间重新渲染组件?

这是完整的课程:

class Timer extends React.Component {
    constructor() {
        super();
        this.state = {
            now: this.getTime(),
            end: this.getTime() + 180
        }
    }

    getTime() {
        return (Date.now()/1000)
    }

    formatTime() {
        let remaining = this.state.end - this.state.now
        let rawMinutes = (remaining / 60) | 0
        let rawSeconds = (remaining % 60) | 0
        let minutes = rawMinutes < 10 ? "0" + rawMinutes : rawMinutes
        let seconds = rawSeconds < 10 ? "0" + rawSeconds : rawSeconds
        let time = minutes + ":" + seconds
        return time
    }

    componentDidMount() {
        setTimeout(this.setState({ now: this.getTime() }), 1000)
    }

    render() {
        return(
            <div id="countdown">
                { this.formatTime() }
            </div>
        )
    }
}

setTimeout第一个参数是function您传递的不是function ,而是它的返回值

为了完成这项工作,您可以使用如下匿名函数包装setState

setTimeout(() => this.setState({ now: this.getTime() }), 1000)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM