javascript - 为什么 componentDidMount 没有被解雇?

标签 javascript reactjs

我有一个函数,当用户单击它时会触发它。该函数调用 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

为什么?

最佳答案

当你的组件被挂载时,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>

关于javascript - 为什么 componentDidMount 没有被解雇?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198832/

相关文章:

reactjs - React组件内的Material ui样式

javascript - React 无法使用forwardRef 和useRef 读取ref 为null 的属性

javascript - 无法解析 : comment: 1.\'comment\' 字段必须是 BSON 类型字符串

javascript - Angular js 路由无法正常工作,没有任何 js 错误

reactjs - 如何处理useState延迟

javascript - 使用 react-router-navigation-prompt 时关于弃用 findDOMNode 的警告

reactjs - react : Stop hook from being called every re-rendering?

javascript - 在 MVC Javascript 函数中,使用 Ajax.ActionLink 不会触发

javascript - 如何跟踪网站在Chrome中崩溃的原因?

javascript - 无法将 jQuery var 获取到 PHP