Javascript TypeError:undefined不是对象(正在计算';this.state.googleResponse.responses[0]';)

Javascript TypeError:undefined不是对象(正在计算';this.state.googleResponse.responses[0]';),javascript,firebase,react-native,expo,google-vision,Javascript,Firebase,React Native,Expo,Google Vision,我在这方面是全新的,我正在使用谷歌视觉和我在世博会上的React原生应用程序来标记文档。我基于这个项目: 我将其编辑为使用文档文本检测 然而,这个错误不断出现 我在代码中使用此.state.googleResponse.responses[0]的唯一位置是: render() { let { image } = this.state; return ( <View style={styles.container}>

我在这方面是全新的,我正在使用谷歌视觉和我在世博会上的React原生应用程序来标记文档。我基于这个项目:

我将其编辑为使用文档文本检测

然而,这个错误不断出现

我在代码中使用此.state.googleResponse.responses[0]的唯一位置是:

    render() {
    let { image } = this.state;

    return (
        <View style={styles.container}>
            <ScrollView contentContainerStyle={styles.contentContainer}>
                <View style={styles.getStartedContainer}>
                    {image ? null : (
                        <Text style={styles.getStartedText}>Smart Text Extractor</Text>
                    )}
                </View>

                <View style={styles.helpContainer}>
                    <View style={{ margin: 20 }}>
                        <Button
                            onPress={this._pickImage}
                            title="Pick an image from Gallery"
                            color="#3b5998"
                        />
                    </View>
                    <Button
                        onPress={this._takePhoto}
                        title="Take a photo"
                        color="#1985bc"
                    />

                    {this.state.googleResponse && (
                        <FlatList
                            data={this.state.googleResponse.responses[0].fullTextAnnotation}
                            extraData={this.state}
                            keyExtractor={this._keyExtractor}
                            renderItem={({ item }) => (
                                <Text style={styles.textText}>
                                    Text Detected: {item.description}
                                </Text>
                            )}
                        />
                    )}

                    {this._maybeRenderImage()}
                    {this._maybeRenderUploadingOverlay()}
                </View>
            </ScrollView>
        </View>
    );
render(){
设{image}=this.state;
返回(
{image?空:(
智能文本提取器
)}
{this.state.googleResponse&&(
(
检测到文本:{item.description}
)}
/>
)}
{this.\u maybeRenderImage()}
{this.\u可能欠加载overlay()}
);
我的全部代码是

    import React, { Component } from 'react';
import {
    View,
    Image,
    Text,
    StyleSheet,
    ScrollView,
    ActivityIndicator,
    Button,
    FlatList,
    Clipboard
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions';
import uuid from 'uuid';
import Environment from './src/config/environment';
import firebase from './src/config/firebase';

//console.disableYellowBox = true;

async function uploadImageAsync(uri) {
    const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            resolve(xhr.response);
        };
        xhr.onerror = function(e) {
            console.log(e);
            reject(new TypeError('Network request failed'));
        };
        xhr.responseType = 'blob';
        xhr.open('GET', uri, true);
        xhr.send(null);
    });

    const ref = firebase
        .storage()
        .ref()
        .child(uuid.v4());
    const snapshot = await ref.put(blob);

    blob.close();

    return await snapshot.ref.getDownloadURL();
}

export default class App extends Component {
    state = {
        image: null,
        uploading: false,
        googleResponse: null
    };

    async componentDidMount() {
        await Permissions.askAsync(Permissions.CAMERA_ROLL);
        await Permissions.askAsync(Permissions.CAMERA);
    }

    organize = array => {
        return array.map(function(item, i) {
            return (
                <View key={i}>
                    <Text>{item}</Text>
                </View>
            );
        });
    };

    _maybeRenderUploadingOverlay = () => {
        if (this.state.uploading) {
            return (
                <View
                    style={[
                        StyleSheet.absoluteFill,
                        {
                            backgroundColor: 'rgba(255,255,255,0.4)',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }
                    ]}
                >
                    <ActivityIndicator color="#fff" animating size="large" />
                </View>
            );
        }
    };

    _maybeRenderImage = () => {
        let { image, googleResponse } = this.state;
        if (!image) {
            return;
        }

        return (
            <View
                style={{
                    marginTop: 20,
                    width: 250,
                    borderRadius: 3,
                    elevation: 2
                }}
            >
                <Button
                    style={{ marginBottom: 10 }}
                    onPress={() => this.submitToGoogle()}
                    title="Analyze!"
                />

                <View
                    style={{
                        borderTopRightRadius: 3,
                        borderTopLeftRadius: 3,
                        shadowColor: 'rgba(0,0,0,1)',
                        shadowOpacity: 0.2,
                        shadowOffset: { width: 4, height: 4 },
                        shadowRadius: 5,
                        overflow: 'hidden'
                    }}
                >
                    <Image source={{ uri: image }} style={{ width: 250, height: 250 }} />
                </View>
                <Text
                    onPress={this._copyToClipboard}
                    onLongPress={this._share}
                    style={{ paddingVertical: 10, paddingHorizontal: 10 }}
                />

                <Text>Raw JSON:</Text>

                {googleResponse && (
                    <Text
                        onPress={this._copyToClipboard}
                        onLongPress={this._share}
                        style={{ paddingVertical: 10, paddingHorizontal: 10 }}
                    >
                        {JSON.stringify(googleResponse.responses)}
                    </Text>
                )}
            </View>
        );
    };

    _keyExtractor = (item, index) => item.description;

    _renderItem = item => {
        <Text>response: {JSON.stringify(item)}</Text>;
    };

    _share = () => {
        Share.share({
            message: JSON.stringify(this.state.googleResponse.responses),
            title: 'Check it out',
            url: this.state.image
        });
    };

    _copyToClipboard = () => {
        Clipboard.setString(this.state.image);
        alert('Copied to clipboard');
    };

    _takePhoto = async () => {
        let pickerResult = await ImagePicker.launchCameraAsync({
            allowsEditing: true,
            aspect: [4, 3]
        });

        this._handleImagePicked(pickerResult);
    };

    _pickImage = async () => {
        let pickerResult = await ImagePicker.launchImageLibraryAsync({
            allowsEditing: true,
            aspect: [4, 3]
        });

        this._handleImagePicked(pickerResult);
    };

    _handleImagePicked = async pickerResult => {
        try {
            this.setState({ uploading: true });

            if (!pickerResult.cancelled) {
                uploadUrl = await uploadImageAsync(pickerResult.uri);
                this.setState({ image: uploadUrl });
            }
        } catch (e) {
            console.log(e);
            alert('Upload failed, sorry :(');
        } finally {
            this.setState({ uploading: false });
        }
    };

    submitToGoogle = async () => {
        try {
            this.setState({ uploading: true });
            let { image } = this.state;
            let body = JSON.stringify({
                requests: [
                    {
                        features: [
                            //{ type: 'TEXT_DETECTION'}, //maxResults: 5 },
                            { type: 'DOCUMENT_TEXT_DETECTION'}//, maxResults: 5 }
                        ],
                        image: {
                            source: {
                                imageUri: image
                            }
                        }
                    }
                ]
            });
            let response = await fetch(
                'https://vision.googleapis.com/v1/images:annotate?key=' +
                    Environment['GOOGLE_CLOUD_VISION_API_KEY'],
                {
                    headers: {
                        Accept: 'application/json',
                        'Content-Type': 'application/json'
                    },
                    method: 'POST',
                    body: body
                }
            );
            let responseJson = await response.json();
            console.log(responseJson);
            this.setState({
                googleResponse: responseJson,
                uploading: false
            });
        } catch (error) {
            console.log(error);
        }
    };

    render() {
        let { image } = this.state;
        console.log(this.state.googleResponse)

        return (
            <View style={styles.container}>
                <ScrollView contentContainerStyle={styles.contentContainer}>
                    <View style={styles.getStartedContainer}>
                        {image ? null : (
                            <Text style={styles.getStartedText}>Smart Text Extractor</Text>
                        )}
                    </View>

                    <View style={styles.helpContainer}>
                        <View style={{ margin: 20 }}>
                            <Button
                                onPress={this._pickImage}
                                title="Pick an image from Gallery"
                                color="#3b5998"
                            />
                        </View>
                        <Button
                            onPress={this._takePhoto}
                            title="Take a photo"
                            color="#1985bc"
                        />

                        {this.state.googleResponse && (
                            <FlatList
                                data={this.state.googleResponse.responses[0].fullTextAnnotation}
                                extraData={this.state}
                                keyExtractor={this._keyExtractor}
                                renderItem={({ item }) => (
                                    <Text style={styles.textText}>
                                        Text Detected: {item.description}
                                    </Text>
                                )}
                            />
                        )}

                        {this._maybeRenderImage()}
                        {this._maybeRenderUploadingOverlay()}
                    </View>
                </ScrollView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ebebeb',
        paddingBottom: 10
    },
    developmentModeText: {
        marginBottom: 20,
        color: 'rgba(0,0,0,0.4)',
        fontSize: 14,
        lineHeight: 19,
        textAlign: 'center'
    },
    contentContainer: {
        paddingTop: 30
    },

    getStartedContainer: {
        alignItems: 'center',
        marginHorizontal: 50,
        marginVertical: 50
    },

    getStartedText: {
        fontSize: 24,
        color: '#000',
        fontWeight: 'bold',
        textAlign: 'center'
    },

    helpContainer: {
        marginTop: 15,
        alignItems: 'center'
    },

    textText: {
        fontSize: 20,
        fontWeight: '600'
    }
});

//export default App;
import React,{Component}来自'React';
进口{
看法
形象,,
文本,
样式表,
滚动视图,
活动指示器,
按钮
平面列表,
剪贴板
}从“反应本机”;
从“世博会图像采集器”导入*作为图像采集器;
从“expo Permissions”导入*作为权限;
从“uuid”导入uuid;
从“/src/config/Environment”导入环境;
从“/src/config/firebase”导入firebase;
//console.disableYellowBox=true;
异步函数uploadImageAsync(uri){
const blob=等待新承诺((解决、拒绝)=>{
const xhr=new XMLHttpRequest();
xhr.onload=函数(){
解析(xhr.response);
};
xhr.onerror=函数(e){
控制台日志(e);
拒绝(新类型错误(“网络请求失败”);
};
xhr.responseType='blob';
open('GET',uri,true);
xhr.send(空);
});
常数参考=火基
.储存
.ref()
.child(uuid.v4());
const snapshot=wait ref.put(blob);
blob.close();
返回wait snapshot.ref.getDownloadURL();
}
导出默认类应用程序扩展组件{
状态={
图像:空,
上传:错,
googleResponse:null
};
异步组件didmount(){
等待权限.askAsync(权限.CAMERA\u ROLL);
wait Permissions.askAsync(Permissions.CAMERA);
}
组织=数组=>{
返回数组.map(函数(项,i){
返回(
{item}
);
});
};
_可能欠加载Overlay=()=>{
if(this.state.uploading){
返回(
);
}
};
_maybeRenderImage=()=>{
让{image,googleResponse}=this.state;
如果(!图像){
返回;
}
返回(
this.submitToGoogle()}
title=“分析!”
/>
原始JSON:
{googleResponse&&(
{JSON.stringify(googleResponse.responses)}
)}
);
};
_keyExtractor=(项,索引)=>item.description;
_renderItem=项目=>{
响应:{JSON.stringify(item)};
};
_份额=()=>{
分享({
消息:JSON.stringify(this.state.googleResponse.responses),
标题:“检查一下”,
url:this.state.image
});
};
_copyToClipboard=()=>{
Clipboard.setString(this.state.image);
警报(“复制到剪贴板”);
};
_takePhoto=async()=>{
让pickerResult=等待ImagePicker.launchCameraAsync({
允许编辑:对,
方面:[4,3]
});
此._handleImagePicked(pickerResult);
};
_pickImage=async()=>{
让pickerResult=等待ImagePicker.launchImageLibraryAsync({
允许编辑:对,
方面:[4,3]
});
此._handleImagePicked(pickerResult);
};
_handleImagePicked=async pickerResult=>{
试一试{
this.setState({upload:true});
如果(!pickerResult.cancelled){
uploadUrl=等待uploadImageAsync(pickerResult.uri);
this.setState({image:uploadUrl});
}
}捕获(e){
控制台日志(e);
警报('上载失败,抱歉:(');
}最后{
this.setState({上传:false});
}
};
submitToGoogle=async()=>{
试一试{
this.setState({upload:true});
设{image}=this.state;
让body=JSON.stringify({
要求:[
{
特点:[
//{type:'TEXT_DETECTION'},//maxResults:5},
{type:'DOCUMENT\u TEXT\u DETECTION'}//,maxResults:5}
],
图片:{
资料来源:{
imageUri:image
}
}
}
]
});
let response=等待获取(
'https://vision.googleapis.com/v1/images:annotate?key=' +
环境['GOOGLE_CLOUD_VISION_API_KEY'],
{
标题:{
接受:'application/json',
“内容类型”:“应用程序”
<FlatList
    data={this.state.googleResponse}
    extraData={this.state}
    keyExtractor={this._keyExtractor}
    renderItem={({ item }) => (
            <Text style={styles.textText}>
                Text Detected: {item.text}
            </Text>
       )}
 />