我有一个功能,当用户单击它时会触发它。该函数调用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
为什么?
答案 0 :(得分:2)
componentDidMount()
方法仅在装入组件时触发。您应该使用componentDidUpdate()
方法,该方法会在您更新组件的状态/属性时触发。
您应该阅读State and Lifecycle的React Docs
请参见下面的代码段
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>