React Native 无法识别Firestore方法

laawzig2  于 2022-11-17  发布在  React
关注(0)|答案(1)|浏览(157)
import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Button,
  Platform,
  Image,
  StatusBar,
  TextInput,
  TouchableOpacity,
} from 'react-native';
import { Header } from 'react-native-elements';
import * as Font from 'expo-font';
import * as Permissions from 'expo-permissions';
import { BarCodeScanner } from 'expo-barcode-scanner';
// import firebase, { firestore } from 'firebase';
// import db from '../components/config';

import 'firebase/firestore';
// import firebase from 'firebase/app';
// // import firebase from 'firebase'

// // import firebase from 'firebase/app';




export default class ScanScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      domState: 'normal',
      hasCameraPermissions: null,
      scanned: false,
    };
  }

  getCameraPermissions = async (domState) => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);

    this.setState({
      /*status === "granted" is true when user has granted permission
          status === "granted" is false when user has not granted the permission
        */
      hasCameraPermissions: status === 'granted',
      domState: domState,
      scanned: false,
    });
  };

  handleBarCodeScanned = async ({ type, data }) => {
    const { domState } = this.state;

    if (domState === 'bookId') {
      this.setState({
        bookId: data,
        domState: 'normal',
        scanned: true,
      });
    }
  };

  addProduct = async () => {
      await firestore()
      .collection('products')
      .doc('panadol')
      .add({
        expiry: '12/23/22',
        activeIngredient:'paracetemol',
      })
      
      .then(() => {
        console.log('Medication added!');
      });
  }



  render() {
    const { domState, scanned, bookId } = this.state;
    if (domState !== 'normal') {
      return (
        <BarCodeScanner
          onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
          style={StyleSheet.absoluteFillObject}
        />
      );
    }
    return (
      <View style={styles.header}>
        <Header
          style={styles.header}
          backgroundColor={'#89CFF0'}
          centerComponent={{
            text: 'Pharmacy App',
            style: { color: '#fff', fontSize: 20 },
          }}
        />

        <Text style={styles.text}>Under Construction</Text>

        <TextInput
          style={styles.textInput}
          placeholder={'Type Barcode'}
          placeholderTextColor={'gray'}
          value={bookId}
          // onChangeText={()=> this.addProduct()}
        />

        <TouchableOpacity
          style={styles.button}
         onPress={() => this.addProduct()}>
          <Text style={styles.buttonText}>Done</Text>
        </TouchableOpacity>

        <Text style={styles.orText}>OR</Text>
        <TouchableOpacity
          style={styles.button}
          onPress={() => this.handleBarCodeScanned()}>
          <Text style={styles.buttonText}>Scan</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#5653D4',
  },
  text: {
    color: 'pink',
    fontSize: 30,
  },

  imageIcon: {
    width: 150,
    height: 150,
    marginLeft: 95,
  },

  header: {
    marginBottom: 100,
  },
  textInput: {
    borderRadius: 10,
    alignContent: 'center',
    borderColor: 'white',
    borderWidth: 3,
    width: '57%',
    height: 50,
    marginLeft: 80,
    marginTop: 80,
  },
  button: {
    backgroundColor: '#89CFF0',
    width: 250,
    justifyContent: 'center',
    alignItems: 'center',
    borderColor: 'white',
    borderRadius: 10,
    borderWidth: 3,
    marginLeft: 45,
    marginTop: 40,
    height: 50,
  },

  buttonText: {
    color: 'white',
    
  },

  orText: {
    marginLeft: 155,
    marginTop: 50,
    
  },
});

在我的代码中,我在Scan.js中有一个名为add item的方法,在该方法中我使用了firestore.collection和. add。我在一个可触摸的不透明度中调用了此函数,因此当我运行代码并尝试单击按钮时,它会向我抛出以下消息:Scan.js:66 Uncatch(in promise)ReferenceError:未定义firestore,并且未捕获引用错误:进程未定义

我尝试将firestore的版本更新到9.0.0,但没有成功。我的应用程序的结果应该是,当我按下完成按钮时,它应该与我的数据库建立连接,并在该字段中添加一个值。

krcsximq

krcsximq1#

您仍然使用版本8语法(命名空间)。您应该使用Firebase的compat库,但我建议您将代码重构为版本9 sytax(模块化),因为compat库是一个临时解决方案,将在未来的主要SDK版本(如版本10或版本11)中完全删除。
为此,您应该按如下方式导入Firebase:

import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

然后初始化Firebase应用程序和Firestore:

const firebaseConfig = {
        // ...
    };
// Initialize Firebase App    
const app = firebase.initializeApp(firebaseConfig);

// Firestore
const db = app.firestore();

然后在访问Firestore时使用变量db

await db
    .collection('products')
    .doc('panadol')
    .add({
        expiry: '12/23/22',
        activeIngredient:'paracetemol',
    })
    .then(() => {
        console.log('Medication added!');
    });

有关更多信息,请查看以下文档:

相关问题