React this become undefined after a function is called by a component, before the this is not undefined. I cannot change the state.
export default class Chart extends React.Component {
constructor(props) {
super(props);
var obj=JSON.stringify(this.props.data);
this.state={data: obj};
}
insert(){
//here it shows undefined
console.log(this)
var json=JSON.parse(this.state.data);
//...
}
render() {
//here shows non-undefined this
console.log(this)
return(
//...
//here calls the fuction that causes the error
<button className="btn" onClick={this.insert}>Add New</button>
</div>
//...
);
}
Here is the error
Uncaught TypeError: Cannot read property 'state' of undefined
at insert (Chart.js:72)