簡體   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