如何解决 React 中 App.js 报错 Uncaught TypeError: Cannot read properties of undefined
在 React 开发过程中,经常会碰到一些报错。这里我们来看一个错误,是在 App.js 中报出来的。错误是这样的:App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading ‘setState’) at onInputChange (App.js:69:1)
下面是产生错误的完整的代码
// 调用 clarifai api接口
const app = new Clarifai.App({
apiKey : 'a2013154seuiasdfdse94302c5bd'
});
class App extends React.Component {
constructor () {
super();
this.state = {
input : '',
imageUrl : '',
}
}
onInputChange(event) {
this.setState({input: event.target.value})
console.log('setState input' + this.state.input);
}
onButtonSubmit() {
this.setState({imageUrl: this.state.input});
app.models.predict(Clarifai.COLOR_MODEL, this.state.input).then(
function(response) {
console.log(response);
},
function(err) {
// 这里处理错误
}
)
}
render(){
return (
<div className="App">
<Particles className="particles" id="tsparticles" options={particlesOptions} />
<Navigation />
<Logo />
<Rank />
<ImageLinkForm onInputChange={this.onInputChange} onButtonSubmit = {this.onButtonSubmit} />
<FaceRecognition imageUrl = {this.state.imageUrl} />
</div>
);
}
}
export default App;
解决这个问题的方法很少。
至于为什么会出现这种情况是因为在上面的代码中没有使用箭头方式,这里我们有两种解决方式
- 我们需要对处理程序进行绑定。如下所示
constructor() { ...code this.onInputChange = this.onInputChange.bind(this) this.onButtonSubmit = this.onInputChange.bind(this) }
- 将方法改为箭头的方式(ES6 语法)。
onInputChange = (event) => { this.setState({input: event.target.value}) console.log('setState input' + this.state.input); } onButtonSubmit = () => { this.setState({imageUrl: this.state.input}); app.models.predict(Clarifai.COLOR_MODEL, this.state.input).then( function(response) { console.log(response); }, function(err) { // 这里处理错误 } ) }
我们可以选择上面两种方式中的任一种。排除各自的环境因素,都可以解决上面的报错。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。