firebase - 将数据发送到 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()
解决方案
在 Fire.js 中使用getter和setter 。
在 Fire.js 中
setRecipient (id){
this.recipientId = id;
}
get getRecipientId () {
return this.recipientId;
}
然后调用Fire.setRecipient(yourId)
Chat.js。
推荐阅读
- javascript - 登录后Reactjs重定向到受保护的页面在身份验证后不起作用
- r - 是否有可能有一个加载条或微调器,该工作需要在闪亮的情况下运行?
- linux - 如何完全卸载 eclipse 基本(ubuntu)?
- python - 查询rpyc中的多个客户端连接
- symfony - 过滤/排序具有多个变量的数组
- google-cloud-platform - OAuth 同意屏幕的待定开发人员操作
- google-bigquery - 在 Big Query 中从 Adwords 转移到 Google Ads API
- python - 如何使用布局解析器将两个块图像合并为一个
- visual-studio - 调试 Code 和 Visual Studio 时如何监控加载时间的差异?
- matomo - 如何在 Matomo 中找到带有掩码 IP 地址的位置(城市)