>我正在尝试构建一个示例应用程序,该应用程序会弹出一个警报,显示 API 响应中的对象数量。警报弹出一次,但之后,我收到此错误
[TypeError: undefined is not an object (evaluating '_this2._OnAlert(count)')]
这是我的代码
import React from 'react';
import { View, Button, Alert } from 'react-native';
import ProductListingItem from './ProductListingItem';
export default class ProductDetailedListingPage extends React.Component {
constructor() {
super();
}
_OnAlert(count){
console.log('_onAlert');
console.log('count = '+ count);
Alert.alert(
'API call success',
count+' objects',
[
{text:'done',onPress: () => { }}
]
);
}
_getResponseFromApi(){
console.log('_getREsponseFromApi called');
var myRequest = new Request('http://mysampleapi.com:8082/listProducts',);
myRequest.method = 'GET';
return fetch(myRequest)
.then((response)=> response.json())
.then((responseJson) => {
var data = responseJson.error;
console.log('data = '+data);
/*console.log(responseJson);*/
var count = Object.keys(responseJson).length;
count = '2';
console.log('count in _getResponseFromApi = '+count);
this._OnAlert(count);
return responseJson;
})
.catch((error) => {
console.log(error);
});
}
componentDidMount () {
console.log('componentDidMount');
this._getResponseFromApi();
}
componentWillMount () {
console.log('componentWillMount');
}
render(){
console.log('render');
return(
<View style = {{
flex:1,
flexDirection:'column',
}}>
<Button style ={{flex:1}}
onPress ={this._getResponseFromApi}
title ="Call"
/>
</View>
);
}
}
问题出在 _OnAlert()
上,它第一次componentDidMount()
运行而没有问题并显示警报对话框,但在onPress()
的实例中,它给了我上述错误。在React和Javascript方面,我是一个菜鸟,尤其是JSX。如何解决此问题?
你应该改变你的构造函数并将方法'_getResponseFromApi'绑定到这里的范围,
constructor() {
super();
this._getResponseFromApi = this._getResponseFromApi.bind(this);
}