简体   繁体   English

反应本机组件异常:未定义不是对象(评估'_this')

[英]React Native Component Exception: undefined is not an object (evaluating'_this')

Iam working on face recognition app using react native 0.63.我正在使用 react native 0.63 开发人脸识别应用程序。 I am runing my project using react-native run-android .我正在使用react-native run-android运行我的项目。 I get Component Exception undefined is not an object(evaluating '_this').我得到未定义的组件异常不是对象(评估'_this')。 I am new to react native and I do not understand the meaning of this error.我是本机反应的新手,我不明白这个错误的含义。 I am following the tutorial for this app but the tutorial is very old and thats why I am unable to update the code to latest version of react native.我正在关注此应用程序的教程,但该教程很旧,这就是为什么我无法将代码更新到 React Native 的最新版本。 Here is the link of tutorial Face Recognition using react native .这是使用 react native 的人脸识别教程的链接。 Please take a look and resolve my issue.请查看并解决我的问题。

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 

在此处输入图片说明

Your component is defined as const Detector = props => { making it a function component.您的组件被定义为const Detector = props => {使其成为功能组件。 Function components don't have a "this" and don't have methods like setState or componentDidMount .函数组件没有“this”,也没有像setStatecomponentDidMount这样的方法。 There are two ways you can solve your problem.有两种方法可以解决您的问题。

  1. Either you make a component that inherits from React.Component .要么创建一个继承自React.Component的组件。 See the docs .请参阅文档 When you do this, this will be available, as well as other component methods like this.setState .当你这样做时, this将可用,以及其他组件方法,如this.setState
  2. Or you use hooks like useState to manage the state inside your components.或者你使用像useState这样的useState来管理组件内部的状态。 docs文档

Which one you choose depends on preference, although hooks is the "newer" way of doing things.您选择哪一个取决于偏好,尽管 hooks 是“较新”的做事方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React-Native / Typescript-未定义不是对象(评估&#39;react_1.default.Component) - React-Native / Typescript - undefined is not an object (evaluating 'react_1.default.Component) TypeError: undefined is not an object (evalating &#39;icons.map&#39;) React-Native - TypeError: undefined is not an object (evaluating 'icons.map') React-Native TypeError: undefined is not an object (评估'_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView') - TypeError: undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView') TypeError: undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[58], "@react-navigation/native").NavigationContainer') - TypeError: undefined is not an object (evaluating '_$$_REQUIRE(_dependencyMap[58], "@react-navigation/native").NavigationContainer') TypeError: undefined is not an object (evaluating 'results.length') in Search Component - TypeError: undefined is not an object (evaluating 'results.length') in Search Component 映射函数 - 未处理的 JS 异常:TypeError:undefined 不是评估映射的对象 - Map Function - Unhandled JS Exception: TypeError: undefined is not an object evaluating map React Native 引用的对象似乎未定义 - React Native referenced object seems to be undefined 在 React Native 功能组件中未定义 useRef.current - useRef.current is undefined in a React Native functional component 箭头 function 在 React-Native 中作为道具传递在传递给它的组件中未定义 - Arrow function passed as prop in React-Native is undefined in component it is passed to React Native &amp;&amp; Firebase &amp;&amp; useContext - &quot;TypeError: null is not an object (evalating &#39;_ref.user&#39;)&quot; with onAuthStateChanged 错误 - React Native && Firebase && useContext - "TypeError: null is not an object (evaluating '_ref.user')" with onAuthStateChanged error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM