【问题标题】:State not being updated in componentDidMountcomponentDidMount 中未更新状态
【发布时间】:2017-04-25 07:32:32
【问题描述】:

我正在尝试在 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。现在,如果 this.setState() (这不是一个函数),您正在传递返回值。换句话说,您在挂载时立即调用this.setState(),而不是在 1000 毫秒之后。

标签: javascript reactjs


【解决方案1】:

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

要完成这项工作,您可以使用这样的匿名函数包装您的 setState:

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

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2016-03-01
    • 1970-01-01
    • 2019-06-23
    • 2018-07-21
    • 1970-01-01
    • 2018-03-22
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多