I am learning React, I find out there's two different ways to define methods in a Component Class.
one way is to define a method as a class method:
handleCategorySelected(category){
this.setState({
category
})
};
but first need to bind method to this in constructor method.
constructor(props) {
super(props);
this.handleCategorySelected = this.handleCategorySelected.bind(this);
}
After bind,I can use it in JSX.
render() {
return <Fragment>
<Footer
onSelect={this.handleCategorySelected}
/>
</Fragment>
}
Otherwise it will throw an Type error:
TypeError: Cannot read property 'setState' of undefined
The second way is more simple,
handleCategorySelected = (category) => {
this.setState({
category
})
};
and after this definition,I can use this method in JSX without bind 'this' in the constructor method;
what's the different between two ways,and why is the first way throws an error without bind 'this',and why is the other way does not? what's the different?