Hello.
Following the technique used in the FreeCodeCamp React course, when I use methods
inside a class
component, I usually do this:
class MyClass-1 extends Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
this.generate = this.generate.bind(this)
}
generate(){
this.setState((prevState) => {
return {
count: prevState.count + 1
}
})
}
render(){
return(
<div>
...
</div>
)
}
}
i.e. I bind the method in the constructor: this.generate = this.generate.bind(this)
However, I’ve also found this way of doing it (based on a bit of someone else’s code):
class MyClass-2 extends Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
generate = ()=> {
this.setState((prevState) => {
return {
count: prevState.count + 1
}
})
}
render(){
return(
<div>
...
</div>
)
}
}
Here, generate
is assigned to an arrow function and there is no need to do any binding in the constructor.
This means less code, but is this (second) method safe?