Ошибка типа: undefined не является функцией (рядом с '..._ fire.default.get ...') - PullRequest
1 голос
/ 08 января 2020

Когда я пытаюсь ввести имя пользователя и затем go на следующем экране для чата в реальном времени, тогда я сталкиваюсь с этой ошибкой.

Вот код для ChatScreen. js file.

Ошибка типа: undefined не является функцией (рядом с '..._ fire.default.get ...').

enter image description here

enter image description here

ChatScreen. js

import React,{Component} from "react";
import {Platform,KeyboardAvoidingView} from 'react-native';
import {GiftedChat}from 'react-native-gifted-chat-fix';
import{SafeAreaView}from 'react-native-safe-area-view';
import Video from 'react-native-video';
import Fire from '../fire';


export default class ChatScreen extends Component{
    state={
        messages:[]
    }
    get user(){
        return{
            _id:Fire.uid,
            name:this.props.navigation.state.params.name
        }
    }
    componentDidMount(){
        Fire.get(message=>this.setState(previous=>({
            messages:GiftedChat.append(previous.messages,message)
        }))
        );
    }
    componentWillUnmount(){
        Fire.off()
    }
    render(){  
        const chat=<GiftedChat messages={this.state.messages} onSend={Fire.send} user={this.user}/>;

        if(Platform.OS=='android'){
            return(
                <KeyboardAvoidingView style={{flex:1}}behavior="padding" keyboardVerticalOffset={30} enabled>
                    {chat}
                </KeyboardAvoidingView>
            );
        }
    return<SafeAreaView style={{flex:1}}>{chat}</SafeAreaView>;            
    }
}

1 Ответ

2 голосов
/ 20 января 2020

Попробуйте изменить код в обоих файлах

Сначала в Fire. js

import firebase from 'firebase'; // 4.8.1

class Fire {
  constructor() {
    this.init();
    this.observeAuth();
  }

  init = () => {
    if (!firebase.apps.length) {
      firebase.initializeApp({
        apiKey:'AIzaSyAPfes9_2EwZESX1puYMUv29yunzK9Ve5U',
        authDomain:'docman-31d96.firebaseapp.com',
        databaseURL: "https://docman-31d96.firebaseio.com",
        projectId: "docman-31d96",
        storageBucket: "docman-31d96.appspot.com",
       messagingSenderId: "649332068608",
        appId:'1:649332068608:android:08c080ee6a4e521f5323e5'
      });
    }
  };

  observeAuth = () =>
    firebase.auth().onAuthStateChanged(this.onAuthStateChanged);

  onAuthStateChanged = user => {
    if (!user) {
      try {
        firebase.auth().signInAnonymously();
      } catch ({ message }) {
        alert(message);
      }
    }
  };

  get uid() {
    return (firebase.auth().currentUser || {}).uid;
  }

  get ref() {
    return firebase.database().ref('messages');
  }

  parse = snapshot => {
    const { timestamp: numberStamp, text, user } = snapshot.val();
    const { key: _id } = snapshot;
    const timestamp = new Date(numberStamp);
    const message = {
      _id,
      timestamp,
      text,
      user,
    };
    return message;
  };

  on = callback =>
    this.ref
      .limitToLast(20)
      .on('child_added', snapshot => callback(this.parse(snapshot)));

  get timestamp() {
    return firebase.database.ServerValue.TIMESTAMP;
  }
  // send the message to the Backend
  send = messages => {
    for (let i = 0; i < messages.length; i++) {
      const { text, user } = messages[i];
      const message = {
        text,
        user,
        timestamp: this.timestamp,
      };
      this.append(message);
    }
  };

  append = message => this.ref.push(message);

  // close the connection to the Backend
  off() {
    this.ref.off();
  }
}

Fire.shared = new Fire();
export default Fire;

, а затем в ChatScreen. js

    import * as React from 'react';
import { Platform , KeyboardAvoidingView,SafeAreaView } from 'react-native';
// @flow
import { GiftedChat } from 'react-native-gifted-chat'; // 0.3.0

import Fire from '../fire';

type Props = {
  name?: string,
};

class ChatScreen extends React.Component<Props> {

  static navigationOptions = ({ navigation }) => ({
    title: (navigation.state.params || {}).name || 'Chat!',
  });

  state = {
    messages: [],
  };

  get user() {
    return {
      name: this.props.navigation.state.params.name,
      _id: Fire.shared.uid,
    };
  }

  render() {
       const chat=<GiftedChat messages={this.state.messages} onSend={Fire.shared.send} user={this.user}/>;

        if(Platform.OS=='android'){
            return(
                <KeyboardAvoidingView style={{flex:1}}behavior="padding" keyboardVerticalOffset={0} enabled>
                    {chat}
                </KeyboardAvoidingView>
            );
        }
    return<SafeAreaView style={{flex:1}}>{chat}</SafeAreaView>; 
  }

  componentDidMount() {
    Fire.shared.on(message =>
      this.setState(previousState => ({
        messages: GiftedChat.append(previousState.messages, message),
      }))
    );
  }
  componentWillUnmount() {
    Fire.shared.off();
  }
}

export default ChatScreen;

Это помогло мне. Это должно работать и для вас.

Чтобы увидеть мое приложение чата, просто посетите https://snack.expo.io/@habibishaikh1 / chatapp

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...