【发布时间】:2017-11-13 09:00:41
【问题描述】:
我正在尝试构建一个示例应用程序,它会弹出一个警报,显示 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,我是个菜鸟。我该如何解决这个问题?
【问题讨论】:
-
从
this._OnAlert(count).bind()中删除bind() -
试过了,现在错误是 [TypeError: undefined is not a function (evalating '_this2._OnAlert(count)')]
-
我也在问题中更改它,以防万一。
-
将
onPress ={this._getResponseFromApi}更改为onPress ={this._getResponseFromApi.bind(this)}或将this._getResponseFromApi=this._getResponseFromApi.bind(this)添加到构造函数中。 -
酷,这也有效。只是出于好奇,为什么从
componentDidMount()调用OnAlert时它会起作用?另外,为什么绑定OnAlert()到this不起作用??
标签: javascript reactjs react-native react-native-android jsx