Javascript 如何使用此按钮重置此react组件中的计时器?
我对ES6有以下基本的ReactJS设置。当我按下重置按钮时,计时器不会返回到“0”。我做错了什么?我是个新手,所以任何代码组织和其他技巧都很受欢迎Javascript 如何使用此按钮重置此react组件中的计时器?,javascript,reactjs,es6-class,Javascript,Reactjs,Es6 Class,我对ES6有以下基本的ReactJS设置。当我按下重置按钮时,计时器不会返回到“0”。我做错了什么?我是个新手,所以任何代码组织和其他技巧都很受欢迎 class App extends Component { constructor(props) { super(props) this.state = { seconds: 0 } this.resetTimer.bind(this) } resetTimer = () => {
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
prop的更改不会更新计时器组件的状态
因此,当道具发生变化时,您需要手动更新状态。您可以使用生命周期方法来实现这一点,如下所示
componentWillReceiveProps(nextProps){
this.state = {
seconds: nextProps.seconds
};
}
此外,您实际上不需要将
此
绑定到重置计时器
,因为重置计时器
是一个。因此,您可以安全地从构造函数中删除this.resetTimer.bind(this)
行。有两种方法可以正确地将this
绑定到resetTimer
第一个选项是在构造函数中执行此操作
constructor(props) {
super(props)
this.state = {
seconds: 0
}
this.resetTimer = this.resetTimer.bind(this)
}
constructor(props) {
super(props)
this.state = {
seconds: 0
}
this.resetTimer = this.resetTimer.bind(this)
}
然后像这样设置按钮
第二种方法是根本不在构造函数中包含this.resetTimer,并在按钮上执行此操作
有两种方法可以将
此
正确绑定到重置计时器
第一个选项是在构造函数中执行此操作
constructor(props) {
super(props)
this.state = {
seconds: 0
}
this.resetTimer = this.resetTimer.bind(this)
}
constructor(props) {
super(props)
this.state = {
seconds: 0
}
this.resetTimer = this.resetTimer.bind(this)
}
然后像这样设置按钮
第二种方法是根本不在构造函数中包含this.resetTimer,并在按钮上执行此操作
不过你还有第二个问题。您的按钮组件可能无法工作,因为没有设置道具
在按钮构造函数中,执行以下操作:
constructor(props) {
super(props);
}
或者将按钮更改为无状态组件,并按如下方式编写:
function Button({onClick, label}) {
return (
<div>
<button onClick={onClick} >{label}</button>
</div>
);
}
试着像上面那样写,看看是否有效。谢谢,即使在进行了更正之后,它仍然不会重置。好吧,为了了解您的问题,我可以看看您的计时器组件吗?