javascript - 状态未在 componentDidMount 中更新

标签 javascript reactjs

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

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

然而,当 componentDidMount 被调用时(我检查了 console.log),状态没有更新。我怎样才能让 componentDidMount 更新状态,从而在新的时间重新渲染组件?

这是完整的类(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>
        )
    }
}

最佳答案

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

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

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

关于javascript - 状态未在 componentDidMount 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41066891/

相关文章:

reactjs - 去抖多个调度 Action

javascript - 如何处理 meteor 调用内或调用后的事件?

reactjs - webpack如何处理导入同一个模块的多个文件React

javascript - D3拖动+链接不动

javascript - 是否可以序列化 Javascript 对象变量并存储到 cookie 中?

javascript - 为什么我的 JavaScript 代码不能在 HTML 文件中运行?

javascript - Angular 表单验证但没有 <form>?

reactjs - 在目标 'FBReactNativeSpec' 和 'Yoga' 之间循环依赖;建筑可能会产生不可靠的结果

reactjs - Redux-form v6 isDirty(和 isPristine)选择器不会在状态更改时触发重新渲染

javascript - 在文本字段中插入文本后聚焦光标