我正在尝试在 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/