首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >setState没有更新DOM

setState没有更新DOM
EN

Stack Overflow用户
提问于 2018-11-10 08:14:15
回答 1查看 1.1K关注 0票数 1

我有这个组件在我的反应应用程序。这基本上是每秒钟更新一次状态。但是<p>{this.state.time}</p>的值并没有改变。我打印状态值,它每秒钟都在变化。

代码语言:javascript
复制
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呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-10 08:24:06

您还需要检查您的状态是否已更改。将以下内容添加到shouldComponentUpdate方法中。

代码语言:javascript
复制
}
else if ( this.state.time !== nextState.time {
  return true;
}

正如文档中提到的

使用shouldComponentUpdate()可以让用户知道一个组件的输出是否不受当前状态变化的影响,或者支持

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53237191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档