Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 屏幕没有更新_Javascript_Reactjs_Timer - Fatal编程技术网

Javascript 屏幕没有更新

Javascript 屏幕没有更新,javascript,reactjs,timer,Javascript,Reactjs,Timer,我希望我的状态每1秒更新一次,但它不起作用。 当我在控制台上记录此秒时,它工作正常,但屏幕未更新 下面是我的代码 import React,{PureComponent}来自'React'; const date=新日期() 让秒数=date.getSeconds() 类计时器扩展了PureComponent{ 陈述={ 秒:秒, } changeSecond=()=>{ this.setState((prevState)=>{ this.state.seconds=prevState.sec

我希望我的
状态每1秒更新一次,但它不起作用。
当我在控制台上记录此
秒时,它工作正常,但屏幕未更新
下面是我的代码

import React,{PureComponent}来自'React';
const date=新日期()
让秒数=date.getSeconds()
类计时器扩展了PureComponent{
陈述={
秒:秒,
}
changeSecond=()=>{
this.setState((prevState)=>{
this.state.seconds=prevState.seconds+1
})
}
componentDidMount(){
this.interval=setInterval(this.changesond,1000)
}
组件将卸载(){
clearInterval(this.interval)
}
render(){
返回(
{this.state.seconds}초
)
}

};看起来像是无效的状态更新。可能是:

changeSecond = () => {
  this.setState((prevState)=> ({ seconds: prevState.seconds + 1 }));
}

从以前的状态更新并返回具有正确对象形状的新状态对象。

您的状态更新不正确。状态设置器的回调表单必须返回新状态:

changeSecond = () => {
    this.setState((prevState) =>
        ({seconds: prevState.seconds + 1})
    );
};
实例:

const{PureComponent}=React;
const date=新日期();
设秒数=date.getSeconds();
类计时器扩展了PureComponent{
陈述={
秒:秒,
};
changeSecond=()=>{
this.setState((prevState)=>
({seconds:prevState.seconds+1})
);
};
componentDidMount(){
this.interval=setInterval(this.changesond,1000);
}
组件将卸载(){
clearInterval(这个.interval);
}
render(){
返回(
{this.state.seconds}초
);
}
};
render(,document.getElementById(“根”))


对于无法运行的示例,请不要使用堆栈片段。但是,您可以轻松地使上述操作处于可运行状态@太好了!请接受答案,以便其他人现在可以解决您的问题。我知道这是一个简短的解释,但如果你觉得它有帮助,那么如果你还没有投票,请不要忘记投票。干杯