将数据发送到React Native中的导入模块

时间:2018-10-14 19:40:28

标签: firebase react-native firebase-realtime-database

我有一个称为Chat.js的模块,该模块导入Fire.js以发送数据(消息进入Chat.js,而Fire.js处理存储)。

我有一个收件人的用户ID,目前仅在Chat.js中可用,但是重要的是要使用Fire.js进行适当存储。

为简洁起见,我删除了一些信息,这是我当前的Chat.js:

import Fire from './Fire';

class Chat extends React.Component<Props> {

  state = {
    messages: [],
  };

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

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

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

export default Chat;

这是我当前的Fire.js:

import firebase from 'react-native-firebase';
class Fire {
  constructor() {
  }



  get ref() {
    var recipient = 'recipientId'
    return firebase.database().ref('messages/' + this.uid + '/' + recipient);
  }

  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)));


  // 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;

我目前需要获取收件人ID,该ID可在chat.js中的

下找到
this.props.navigation.state.params.uid

进入Fire.js行:

get ref() 
    {
    var recipient = 'recipientId'

我似乎无法将此uid放入get ref()

1 个答案:

答案 0 :(得分:1)

在Fire.js中使用 getter setter

在Fire.js中

setRecipient (id){
    this.recipientId = id;
}
get getRecipientId () {
    return this.recipientId;
}

然后在Chat.js中调用Fire.setRecipient(yourId)