React-Native Error - “[TypeError:undefined不是对象(评估'_this2._OnAlert(count)')]”

时间:2017-11-13 09:00:42

标签: javascript reactjs react-native react-native-android jsx

我正在尝试构建一个示例应用程序,该应用程序弹出一个警报,显示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,我是一个菜鸟。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您应该更改构造函数并将方法'_getResponseFromApi'绑定到此处的范围,

constructor() {
super();
  this._getResponseFromApi = this._getResponseFromApi.bind(this);
}