【问题标题】:React Native Component Exception: undefined is not an object (evaluating'_this')React Native 组件异常:未定义不是对象(评估'_this')
【发布时间】:2020-10-22 06:08:55
【问题描述】:

我正在使用 react native 0.63 开发人脸识别应用程序。我正在使用react-native run-android 运行我的项目。我得到未定义的组件异常不是对象(评估'_this')。我是本机反应的新手,我不明白这个错误的含义。 我正在关注这个应用程序的教程,但教程很旧,这就是为什么我无法将代码更新到最新版本的 react native。这是教程的链接 Face Recognition using react native。请查看并解决我的问题。

import React from 'react';

import {StyleSheet,Text,View,Image} from 'react-native';
 
import NativeModules, { ImagePickerManager } from 'react-native';
 
import Button from './Button';
 
import RNFetchBlob from 'react-native-fetch-blob';
 
import _ from 'lodash';
 
const Detector = props => {

this.state = {
    photo_style: {
        position: 'relative',
        width: 480,
        height: 480
    },
    has_photo: false,
    photo: null,
    face_data: null
};

return (
  <View style={styles.container}>
     
    <Image
        style={this.state.photo_style}
        source={this.state.photo}
        resizeMode={"contain"}
    >
        { this._renderFaceBoxes.call(this) }
    </Image>
 
    <Button
        title="Pick Photo"
        onPress={()=>{this._pickImage.bind(this)}}
        button_styles={styles.button}
        button_text_styles={styles.button_text} />

    { this._renderDetectFacesButton.call(this) }

  </View>
);


}

  const _pickImage = () => {
 
this.setState({
    face_data: null
});

ImagePickerManager.showImagePicker(this.props.imagePickerOptions, (response) => {
     
  if(response.error){
    alert('Error getting the image. Please try again.');
  }else{
     
    let source = {uri: response.uri};

    this.setState({
      photo_style: {
        position: 'relative',
        width: response.width,
        height: response.height
      },
      has_photo: true,
      photo: source,
      photo_data: response.data
    });
     
  }
});



}
 
  const _renderDetectFacesButton = () => {
    if(this.state.has_photo){
        return  (
            <Button
                title="Detect Faces"
                onPress={()=>{this._detectFaces.bind(this)}}
                button_styles={styles.button}
                button_text_styles={styles.button_text} />
        );
    }
  }
 
  const _detectFaces = () => {
RNFetchBlob.fetch('POST', 'https://api.projectoxford.ai/face/v1.0/detect?returnFaceId=true&returnFaceAttributes=age,gender', {
    'Accept': 'application/json',
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': this.props.apiKey
}, this.state.photo_data)
.then((res) => {
    return res.json();      
})
.then((json) => {
     
    if(json.length){
        this.setState({
            face_data: json
        });
    }else{
        alert("Sorry, I can't see any faces in there.");
    }
     
    return json;
})
.catch (function (error) {
    console.log(error);
    alert('Sorry, the request failed. Please try again.' + JSON.stringify(error));
});
 



}
 
  const _renderFaceBoxes = () => {
if(this.state.face_data){

    let views = _.map(this.state.face_data, (x) => {
         
        let box = {
            position: 'absolute',
            top: x.faceRectangle.top,
            left: x.faceRectangle.left
        };

        let style = { 
            width: x.faceRectangle.width,
            height: x.faceRectangle.height,
            borderWidth: 2,
            borderColor: '#fff',
        };
         
        let attr = {
            color: '#fff',
        };

        return (
            <View key={x.faceId} style={box}>
                <View style={style}></View>
                <Text style={attr}>{x.faceAttributes.gender}, {x.faceAttributes.age} y/o</Text>
            </View>
        );
    });

    return <View>{views}</View>
}



 }
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    alignSelf: 'center',
    backgroundColor: '#ccc'
  },
  button: {
    margin: 10,
    padding: 15,
    backgroundColor: '#529ecc'
  },
  button_text: {
    color: '#FFF',
    fontSize: 20
  }
});
 
export default Detector 

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    您的组件被定义为const Detector = props =&gt; {,使其成为一个函数组件。 函数组件没有“this”,也没有像setStatecomponentDidMount 这样的方法。有两种方法可以解决您的问题。

    1. 要么创建一个继承自React.Component 的组件。请参阅docs。执行此操作时,this 以及其他组件方法(如 this.setState)将可用。
    2. 或者您使用像useState 这样的钩子来管理组件内部的状态。 docs

    您选择哪一种取决于偏好,尽管钩子是“较新”的做事方式。

    【讨论】:

    • 谢谢@Thomas。使用 React.Component 解决我的问题。
    • 现在我收到此错误undefined is not an object(evaluating 'this._renderFaceBoxes.call')。你能解决这个问题吗?
    猜你喜欢
    • 2018-03-05
    • 2021-06-22
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多