react报错 TypeError: Cannot read property 'setState' of undefined
class drag extends Component {
constructor(props) {
super(props);
this.state = {
activeDrags: 0
}
this.onStart = this.onStart.bind(this);
//不加此行会报TypeError错误
}
onStart() {
this.setState({activeDrags: ++this.state.activeDrags});
}
render() {
const dragHandlers = {onStart: this.onStart};
return (
<div>
<Draggable {...dragHandlers}>
<div className="box">你可以随意拖动我</div>
</Draggable>
</div>
);
}
}
export default drag;
开始拖动时,到了onStart()方法中的this已经不是组件里的this了
第一种方法可以手动绑定:
this.onStart = this.onStart.bind(this);添加它就可以解决.
第二种方法是使用箭头函数:
onStart= ( ) => {
this.setState({activeDrags: ++this.state.activeDrags});
}
箭头函数除了代码少,与普通函数最大的不同就是:this是由声明该函数时候定义的,一般是隐性定义为声明该函数时的作用域this。
箭头函数最大的作用是使得this从正常情况下的动态作用域(根据运行位置确定值)变成了静态作用域(根据定义位置确定值,也就是词法作用域)。
本文探讨了在React组件中,如何避免因this指向错误导致的TypeError。通过两种方法:手动绑定this和使用箭头函数,确保setState方法能正确调用。文章详细解释了为什么在构造函数中绑定this是必要的,以及箭头函数如何改变this的默认行为。

被折叠的 条评论
为什么被折叠?



