我有这个组件在我的反应应用程序。这基本上是每秒钟更新一次状态。但是<p>{this.state.time}</p>的值并没有改变。我打印状态值,它每秒钟都在变化。
import React from 'react'
import './style.css'
class List extends React.Component{
constructor(props){
super(props)
this.state = {
time:420
}
this.handleCountdown = this.handleCountdown.bind(this)
}
handleCountdown(){
console.log('4')
console.log(this.state)
setInterval(()=>{
this.setState({time:this.state.time-1})
console.log('here')
console.log(this.state)
},1000)
}
shouldComponentUpdate(nextProps, nextState){
console.log('1')
if(this.props.start != nextProps.start){
console.log('in')
if(nextProps.start == false){
this.setState({time:420})
console.log('2')
return true
}
else if(nextProps.start == true){
this.handleCountdown()
console.log('3')
return true
}
}else{
return false
}
}
render(){
{console.log(this.state)}
return(
<div className="test-clock">
<p>{this.state.time}</p>
<p className='test-clock-subheading'>{this.props.start=='true'?'Min remaining':'Start sudo contest'}</p>
</div>
)
}
}
export default List它是子组件。我将它导入父级,然后使用它。有人能说出DOM为什么不更新吗?
this.forceUpdate()将更新DOM。但是为什么this.setState()不更新DOM呢?
发布于 2018-11-10 08:24:06
您还需要检查您的状态是否已更改。将以下内容添加到shouldComponentUpdate方法中。
}
else if ( this.state.time !== nextState.time {
return true;
}正如文档中提到的
使用
shouldComponentUpdate()可以让用户知道一个组件的输出是否不受当前状态变化的影响,或者支持。
https://stackoverflow.com/questions/53237191
复制相似问题