【发布时间】:2020-04-04 18:29:30
【问题描述】:
上下文:我正在构建一个计时器应用,我有两个组件,App.js(父)和 Configuration.js(子)。
我想在 Configuration.js 中获取一个状态,该状态最初设置为 timerSecond: this.props.timerSecond(通过 props 从 App.js 中提取)并在父组件中更新相同的状态正在更新 在子组件中。
这是我的 App.js 的一部分:
class App extends React.Component {
constructor() {
super();
this.state = {
breakLength: 5,
sessionLength: 25,
timerMinute: 25,
timerSecond: 0,
isPlay: false
}
还有我的 Configuration.js:
class Configuration extends React.Component {
constructor(props) {
super(props);
this.state = {
isSession: true,
timerSecond: this.props.timerSecond,
intervalId: 0
};
this.playTimer = this.playTimer.bind(this);
this.decreaseTimer = this.decreaseTimer.bind(this);
}
// PLAY
playTimer() {
let intervalId = setInterval(this.decreaseTimer, 1000);
this.props.onPlayStopTimer(true);
this.setState({
intervalId: intervalId
})
}
// Decrease seconds
decreaseTimer() {
switch(this.state.timerSecond) {
case 0:
if(this.props.timerMinute === 0) {
if(this.state.isSession) {
this.setState({
isSession: false
});
this.props.toggleInterval(this.state.isSession);
} else {
this.setState({
isSession: true
});
this.props.toggleInterval(this.state.isSession);
}
} else {
this.props.updateTimerMinute()
this.setState({
timerSecond: 59
})
}
break;
default:
this.setState((prevState) => {
return {
timerSecond: prevState.timerSecond - 1,
}
})
break;
}
}
本质上- 每次秒数从 59 逐渐减少时,状态 timerSecond 都会在 Configuration.js 中成功更改,但我不确定如何将该更新推送到父级 (App.js)。我需要它在 App.js 中动态更新,因为我有另一个组件从同一状态 (timerSecond) 拉出并在页面上显示计时器滴答声。
我已经阅读过诸如 componentDidUpdate() 之类的生命周期方法,但我不确定如何在这种情况下使用它?每次尝试时,我都会不断收到无限循环错误消息。我也遇到过这段代码
componentDidUpdate(prevProps, prevState){
if(prevState.searchTerm !== this.state.searchTerm) {
this.props.onSearchChange(this.state.searchTerm)
}
}
在this posting,但我不确定这是否有助于/适用于我的计时器应用程序的动态方面?
【问题讨论】:
标签: reactjs dynamic timer setstate