javascript - 在 React 有状态组件中调用 setInterval 方法时日期对象未更新
问题描述
我是新手,我正在尝试练习有状态的组件。我的目标是使用 setInterval 方法更新小时、分钟和秒。我第一次尝试使用
this.setState({
seconds: date.getSeconds()
})
但无济于事。然后我尝试使用 prevState 方法。有谁知道我错过了什么?
这是我的完整代码:
import InputDisplay from './components/InputDisplay';
class Stateful extends Component {
constructor(props){
super(props);
this.state = {
inputName: "",
inputValue: "Juice",
hour: 0,
minute: 0,
seconds: 0
}
}
componentDidMount() {
this.startClock();
}
handleOnChangeInput = (e) => {
let {name, value} = e.target
this.setState({
[name]: name,
inputValue: value
})
}
startClock = () =>{
const date = new Date();
setInterval(() =>{
console.log(this.state.seconds);
let seconds = date.getSeconds()
console.log(seconds);
this.setState(prevState => {
return {
hour: prevState.hour = date.getHours(),
minute: prevState.minute = date.getMinutes(),
seconds: prevState.seconds = date.getSeconds()
}
})
}, 1000
)
}
render(){
return(
<div>
<h1>Hello this is Stateful Input: {this.state.inputValue} </h1>
<InputDisplay
name={this.state.inputName}
value= {this.state.inputValue}
onChange= {this.handleOnChangeInput}
/>
<h3>H:{this.state.hour} M:{this.state.minute} S:{this.state.seconds}</h3>
</div>
)
}
}
export default Stateful;```
解决方案
我发现您的代码存在一些问题。
1) 设置状态不正确
2)您需要将intervalId存储在状态中并清除组件卸载的间隔
试试这样:
import InputDisplay from './components/InputDisplay';
class Stateful extends Component {
constructor(props){
super(props);
this.state = {
inputName: "",
inputValue: "Juice",
hour: 0,
minute: 0,
seconds: 0,
intervalId: null,
}
}
componentDidMount() {
const intervalId = setInterval(this.startClock, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
}
componentWillUnmount() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
}
startClock = () => {
const date = new Date();
const hour = date.getHours()
const minute = date.getMinutes()
const seconds = date.getSeconds()
this.setState({
hour,
minute,
seconds
})
}
handleOnChangeInput = (e) => {
let {name, value} = e.target
this.setState({
[name]: name,
inputValue: value
})
}
render(){
return(
<div>
<h1>Hello this is Stateful Input: {this.state.inputValue} </h1>
<InputDisplay
name={this.state.inputName}
value= {this.state.inputValue}
onChange= {this.handleOnChangeInput}
/>
<h3>H:{this.state.hour} M:{this.state.minute} S:{this.state.seconds}</h3>
</div>
)
}
}
export default Stateful;
推荐阅读
- javascript - d3 - 无法绘制圆圈来表示音频剪辑的频率与时间的关系
- c - 如何删除数组的内容以便稍后使用 strcat()?
- php - PHP:mysqli_connect - 使用本地主机套接字时没有这样的文件或目录
- javascript - 如何让 eslint/vscode-eslint 停止 linting .eslintrc?
- kubernetes - 是否可以运行 kubeadm init 命令忽略生成证书?
- sql - 查询以输出每种类型的最大电影票
- python - 从张量流中的向量构造成对矩阵
- mysql - 尝试运行一个查询,向我们显示出站潜在客户与入站潜在客户的百分比
- angular - Angular6 *ngFor表与对象中的对象
- json - 跨多个字段收集给定键的值 - Apache Spark (Scala)