this.setState is undefined
also you can bind this in constructor
like this
class MyClass extends React.Component {
constructor(props){
super(props);
this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick(){
console.log("Hello from here");
}
render() {
return (
<button onClick={this.handleButtonClick}>Click me</button>
);
}
}
Let me write this in detail. As I had to waste a lot of time in researching it & I don't want anyone to repeat this...
If you dont use Arrow Function you have to bind this
like Line '9'
class MyClass extends React.Component {
handleButtonClick(){
console.log("Hello from here");
};
render() {
return (
<button onClick={this.handleButtonClick.bind(this)}>Click me</button>
);
}
}
Another way is using ES6 Arrow function. You need not bind 'this' in this case. Installing 'babel stage-1 preset' will support this.
Run the command below in your project:
npm i babel-preset-stage-1 --save
Your .babelrc will look like this. Specially 'stage-1' in the preset.
{
"presets": ["es2015", "react", "stage-1"],
"env": {
"development": {
"plugins": ["react-hot-loader/babel"]
}
}
}
Your component will be like this, as I said:
class MyClass extends React.Component {
handleButtonClick = () => {
console.log("Hello from here");
};
render() {
return (
<button onClick={this.handleButtonClick}>Click me</button>
);
}
}
The problem was: I had that ERROR: this.setState is not a function
Given i was binding my function to the state in component constructor, like this:
this.getRequestData = this.getRequestData.bind(this);
and my function was:
getRequestData(){
axios.post('http://example.com/getInfo', jsonData)
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
this.setState({ stateVaribale });
})
}
the solution is to use arrow functions
instead of using keyword
function in the axios request, cause it's confusing to react to refer to the function in axios request instead of the component state.
getRequestData(){
axios.post('http://example.com/getInfo', jsonData)
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error);
});
this.setState({ stateVaribale });
})}
When you extend
React.Component
with ES2015 class syntax you need to bind your action handlers to a context of your class.
Try this: onChange={e => _handleTextChange(e)}
Generally, it's better not to use arrow functions or bind
methods inside render
as it generates a new copy of the function on any render
call. Move function declaration to the class constructor
.
I personally prefer to use arrow functions as class properties in this case
class MyClass extends React.Component {
handleClick = () => {
// your logic
};
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
}
It's not a part of ES2015 specification but babel stage-0 preset supports this syntax
You can read more about context binding in React in this article