I have several questions about this challenge. I passed it already, but I don’t quite understand it fully.
-
Why do we need to ‘clean up’ the component?
-
What does it mean when the component are unmounted and destroyed?
-
In this challenge, componentWillUnmount()
is used to remove the event listener, why do we need to remove it?
-
Even though I implemented componentWillUnmount()
, when I press the enter key, it still renders. And on top of that, multiple h1
s are rendered. Why is that happening? I had assumed it would just be a single h1
with the state’s message property in it.
Could you give me a real-life example of when you only use a code one time and then delete/clean it? Below is the code.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
};
this.handleEnter = this.handleEnter.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
}
// change code below this line
componentDidMount() {
}
componentWillUnmount() {
}
// change code above this line
handleEnter() {
this.setState({
message: this.state.message + 'You pressed the enter key! '
});
}
handleKeyPress(event) {
if (event.keyCode === 13) {
this.handleEnter();
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
};
The reason why you have previous messages left there is because your setState is this.setState({ message: this.state.message + 'You pressed the enter key! '
If you remove the this.state.message
and only setState as message: 'You pressed the enter key! '
then you will only have one message.
2 Likes
Could you please explain why this solution fixes the problem?
Is because the “this.state.message” is carrying over the previous value?