简介:React中使用setState出现:TypeError: this.setState is not a function
learn-anything | 2018年12月13日00:30:17
【问题】:回调函数里面调用this.setState方法出现以下错误:
TypeError: this.setState is not a function
【解决方案】:在回调函数处使用bind,带入如下:
constructor(props) {
super(props);
this.state = {
name:1
}
}
click(){
let _name = this.state.name
console.log('click before')
this.setState({
name:++_name
},()=>{
console.log('click 回调')
})
console.log('click behind')
}
render() {
console.log('render')
return (
<div onClick={this.click.bind(this)}>
{this.state.name}
</div>
)
}
参考链接:
网友评论