Reputation: 3705
I have a function which fires when the user clicks on it. The function calls setState, and the component rerenders itself. The only problem is that componentDidMount() does not get fired. Here's the code:
//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
Why?
Upvotes: 0
Views: 915
Reputation: 3403
The componentDidMount()
method just get trigerred when your component is mounted. You should use componentDidUpdate()
method, that gets triggered when you update the state/props of your component.
You should read the React Docs for State and Lifecycle
See the snippet below:
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>
Upvotes: 2