Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - React - uncaught TypeError:无法读取undefined的属性'setState'(React - uncaught TypeError: Cannot read property 'setState' of undefined)

I am getting the following error(我收到以下错误)

Uncaught TypeError: Cannot read property 'setState' of undefined(未捕获的TypeError:无法读取未定义的属性“setState”) even after binding delta in the constructor.(甚至在构造函数中绑定delta之后。) class Counter extends React.Component { constructor(props) { super(props); this.state = { count : 1 }; this.delta.bind(this); } delta() { this.setState({ count : this.state.count++ }); } render() { return ( <div> <h1>{this.state.count}</h1> <button onClick={this.delta}>+</button> </div> ); } }   ask by Dangling_pointer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is due to this.delta not being bound to this .(这是因为this.delta不受this 。)

In order to bind set this.delta = this.delta.bind(this) in the constructor:(为了在构造函数中绑定set this.delta = this.delta.bind(this) :) constructor(props) { super(props); this.state = { count : 1 }; this.delta = this.delta.bind(this); } Currently, you are calling bind.(目前,您正在调用bind。) But bind returns a bound function.(但是bind返回一个绑定函数。) You need to set the function to its bound value.(您需要将函数设置为其绑定值。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...