Javascript 无法更改反应状态
React在组件调用函数后,在this未定义之前,此值将变为未定义。我不能改变现状Javascript 无法更改反应状态,javascript,reactjs,this,Javascript,Reactjs,This,React在组件调用函数后,在this未定义之前,此值将变为未定义。我不能改变现状 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 sho
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>
//...
);
}
您正在失去以下范围:
onClick={this.insert}
照办
onClick={() => this.insert()}
要保留它。请使用ES6函数,下面是一个工作示例
onClick={() => this.insert()}