我正在尝试将props传递给使用componentWillReceiveProps时工作的组件,但是一旦计数器完成,它就会调用clearInterval(this.intervalId);
但是一旦我再次更改输入,计数器就不会再次启动。如何将更新的道具传递回组件?
组件代码;
class Stopwatch extends Component {
constructor(props) {
super(props);
this.state = {
currentCount: this.props.counter,
hours: 0,
minutes: 0,
seconds: 0
}
}
componentWillMount() {
this.timer(this.props.counter);
}
timer() {
this.setState({
currentCount: this.state.currentCount - 1
})
const seconds = Math.floor(this.state.currentCount % 60);
const minutes = Math.floor((this.state.currentCount/60) % 60);
const hours = Math.floor((this.state.currentCount/3600) % 3600);
this.setState({hours, minutes, seconds});
if (this.state.currentCount < 1) {
clearInterval(this.intervalId);
}
}
componentDidMount() {
this.intervalId = setInterval(this.timer.bind(this), 1000);
}
leading0(num) {
return num < 10 ? '0' + num : num;
}
componentWillReceiveProps(nextProps){
if(nextProps.counter !== this.props.counter){
this.setState ({currentCount: nextProps.counter})
}
}
render() {
return (
<div>
<div>Hours {this.leading0(this.state.hours)}</div>
<div>Minutes {this.leading0(this.state.minutes)}</div>
<div>Seconds {this.leading0(this.state.seconds)}</div>
</div>
)
主要代码;
class App extends Component {
constructor(props) {
super(props);
this.state = {
deadline: 'December 25, 2018',
newDeadline: '',
counter: 75,
newCounter: ''
};
}
changeDeadline() {
this.setState({deadline: this.state.newDeadline});
}
changeNumber(e) {
this.setState({counter: this.state.newCounter});
}
render() {
return (
<div className='App'>
<div className='App-title'>Countdown to {this.state.deadline}</div>
<Clock
deadline={this.state.deadline}
/>
<Form inline>
<FormControl
className="Deadline-input"
placeholder='New Date'
onChange={event => this.setState({newDeadline: event.target.value})}
/>
<Button onClick={() => this.changeDeadline()}>Submit</Button>
</Form>
<div>Stopwatch From { this.state.counter } Seconds</div>
<Stopwatch
counter={this.state.counter}
/>
<Form inline>
<FormControl
className="Deadline-input"
placeholder='New Number'
onChange={event => this.setState({newCounter: event.target.value})}
/>
<Button onClick={() => this.changeNumber()}>Submit</Button>
</Form>
</div>
)
}
先谢谢
答案 0 :(得分:1)
componentDidMount
函数调用一次,如果你想重置道具改变的计数器,你应该在componentWillReceiveProps
函数中执行
class Stopwatch extends Component {
// ...
resetInterval() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
this.intervalId = setInterval(this.timer.bind(this), 1000);
}
componentWillReceiveProps(nextProps){
if(nextProps.counter !== this.props.counter){
this.setState ({currentCount: nextProps.counter})
// reset interval
this.resetInterval()
}
}
//...
}