首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么componentDidMount没有被解雇?

为什么componentDidMount没有被解雇?
EN

Stack Overflow用户
提问于 2018-07-06 03:45:32
回答 1查看 801关注 0票数 0

我有一个函数,当用户点击它时会触发它。该函数调用setState,然后组件重新呈现自身。唯一的问题是componentDidMount()不会被触发。代码如下:

//the element which fires removeElem
    <div onClick={this.removeElem}>
        -
    </div>
    
//the removeElem function gets called
    removeElem = () => {
        this.setState({status: 'deleted'})
    }
//the component renders, the state has been changed
    render(){
        console.log(this.state.status) //the right value is logged after removeElem()
        return(
        //...
//componentDidMount
    componentDidMount(){console.log("mounted")} //not logging

为什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-06 03:54:27

componentDidMount()方法只是在挂载组件时触发。您应该使用componentDidUpdate()方法,该方法在您更新组件的状态/属性时触发。

您应该阅读State and Lifecycle的React文档

请看下面的代码片段:

class App extends React.Component {
    state = { status: 'active' }
    //componentDidMount
    componentDidMount(){console.log("mounted")}
   //componentDidUpdate
    componentDidUpdate(){console.log("new status:",this.state.status)}
    //the removeElem function gets called
    removeElem = () => {
        this.setState({status: 'deleted'})
    }
    //the component renders, the state has been changed
    render(){
        console.log(this.state.status) //the right value is logged
        return( <button onClick={this.removeElem}>
                Trigger it
        </button>);
    }
}

ReactDOM.render(<App/>,document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>

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

https://stackoverflow.com/questions/51198832

复制
相关文章

相似问题

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