简体   繁体   English

状态未在componentDidMount中更新

[英]State not being updated in componentDidMount

I'm attempting to build a countdown timer in React. 我正在尝试在React中建立一个倒数计时器。 My understanding was that componentDidMount will be called immediately after render , and so I can use it to call setState with the current time after a one second delay. 我的理解是componentDidMount将在render之后立即被调用,因此我可以使用它在延迟一秒钟后使用当前时间调用setState Like so: 像这样:

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

However, while componentDidMount is being called (I checked with console.log ), the state is not updating. 但是,在调用componentDidMount (我通过console.log进行了检查),状态没有更新。 How can I get componentDidMount to update the state and thus re-render the component with a new time? 如何获取componentDidMount来更新状态,从而用新的时间重新渲染组件?

Here is the full class: 这是完整的课程:

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>
        )
    }
}

first parameter of setTimeout is function - what you are passing is not a function , but its return value setTimeout第一个参数是function您传递的不是function ,而是它的返回值

to make this work you could wrap your setState with anonymous function like this: 为了完成这项工作,您可以使用如下匿名函数包装setState

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

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

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