gpt4 book ai didi

javascript - 如何让这个按钮来重置这个 react 组件中的计时器?

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:33 25 4
gpt4 key购买 nike

我有以下 ES6 的基本 ReactJS 设置。当我按下重置按钮时,计时器不会回到“0”。我究竟做错了什么?我对 React 还很陌生,所以任何代码组织和其他技巧也很感激。

class App extends Component {
constructor(props) {
super(props)
this.state = {
seconds: 0
}
this.resetTimer.bind(this)
}
resetTimer = () => {
this.setState({seconds: 0})
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Button label="Start"/>
<Button label="Stop"/>
<Button label="Reset" onClick={this.resetTimer} />
<Timer seconds={this.state.seconds} />
</div>
);
}
}

class Button extends Component {
render() {
return(
<div>
<button onClick={this.props.onClick} >{this.props.label}</button>
</div>
);
}
}

class Timer extends Component {
constructor(props) {
super(props)
this.state = {
seconds: this.props.seconds
};
}
componentDidMount() {
this.timerId = setInterval(
() => this.tick(),
1000
);
}
tick() {
this.setState({ seconds: this.state.seconds + 1});
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return (
<div>{secToMin(this.state.seconds)}</div>
);
}
}

export default App;

最佳答案

问题出在您的代码中,您仅将 seconds 属性值分配给构造函数中的 state 。构造函数仅被调用一次,之后,对 seconds 属性的更改不会更新 Timer 组件的状态。

所以当 props 改变时你需要手动更新状态。您可以使用componentWillReceiveProps()生命周期方法执行此操作如下。

componentWillReceiveProps(nextProps){
this.state = {
seconds: nextProps.seconds
};
}

此外,您实际上不需要将 this 绑定(bind)到 resetTimer,因为 resetTimerarrow function 。因此,您可以安全地从构造函数中删除 this.resetTimer.bind(this) 行。

关于javascript - 如何让这个按钮来重置这个 react 组件中的计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44013777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com