When you’re passing onClick handler you’re changing context from your component to a button element, meaning when your handler will be invoked this will refer to a button which in turn doesn’t have .setState method you will try to call. In order to fix it you basically have two options:
- Explicetely bind
thisinside method to your component - Use class fields creating methods with arrow function:
class MyComponent extends React.Component {
state = {
name: 'Initial State'
};
handleClick = () => {
this.setState({
name: 'React Rocks!'
});
};
render() { /* As usual */ }
}
Arrow function does not have concept of this and this inside arrow function always refers to outer context at declaration time, which will always be your component (exactly what you need).
You’re rewriting your method on every contruction event (when constructor is invoked). It’s nothing different than this:
a = a.concat(b);
You can learn about .bind() here: Function.prototype.bind() - JavaScript | MDN