gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:53:52 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com