首页 > 解决方案 > 将数据发送到 React Native 中的导入模块

问题描述

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

我有一个当前仅在 Chat.js 中可用的收件人用户 ID,但访问 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,可以在chat.js 下

this.props.navigation.state.params.uid

进入 Fire.js 行:

get ref() 
    {
    var recipient = 'recipientId'

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

标签: firebasereact-nativefirebase-realtime-database

解决方案


在 Fire.js 中使用gettersetter 。

在 Fire.js 中

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

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


推荐阅读