firebase - this.props 在类中未定义
问题描述
我正在使用 Firebase 和 React-Native 创建一个聊天应用程序。现在我正在尝试动态更改对 Firebase 数据库的引用。但我无法访问类内的状态。错误状态 this.props 未定义的地方。
import firebase from 'firebase';
import { connect } from 'react-redux';
class Fire {
constructor() {
this.init();
this.observeAuth();
}
init = () =>
firebase.initializeApp({
apiKey: 'AIzaSyBN7GqrGYOyhykm26wyRpXYNe0LBx6wrec',
authDomain: 'kc-connect.firebaseapp.com',
databaseURL: 'https://kc-connect.firebaseio.com',
projectId: 'kc-connect',
storageBucket: '',
messagingSenderId: '526601747673',
appId: "1:526601747673:web:f510e43766eb970c"
});
observeAuth = () => {
firebase.auth().onAuthStateChanged(this.onAuthStateChanged);
}
onAuthStateChanged = user => {
if (!user) {
try {
console.log('user', user);
firebase.auth().signInAnonymously();
} catch ({ message }) {
console.log('user', user);
alert(message);
}
}
};
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get ref() {
return firebase.database().ref('messages/' + this.props.userInfo.id);
}
parse = snapshot => {
const { timestamp: numberStamp, text, user } = snapshot.val();
const { key: _id } = snapshot;
const timestamp = new Date(numberStamp);
const message = {
_id,
timestamp,
text,
user,
};
console.log(message);
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
};
console.log(message);
this.append(message);
}
};
append = message => this.ref.push(message);
// close the connection to the Backend
off() {
this.ref.off();
}
}
Fire.shared = new Fire();
mapStateToProps = (state) => {
return {
userInfo: state.auth.userInfo
}
}
export default connect(mapStateToProps, {})(Fire);
在获取 ref 函数中,我无法使用 this.props.userInfo.id 访问状态。我将如何做?
解决方案
要定义一个 React 组件类,你需要扩展 React.Component:
import React from 'react';
import {Text} from 'react-native
class Welcome extends React.Component {
render() {
return <Text>Hello, {this.props.name}</Text>;
}
}
推荐阅读
- swift - How do I stop the swift playground for a long running process?
- ios - How to switch on a RawRepresentable enum type in Swift
- python - 如何从电子邮件中下载文件并将其保存在 C:\
- python - 在 python 中跨进程共享数据
- python - “OSError: [Errno 22] Invalid argument:” 尝试使用 save() 保存编辑过的工作簿时
- python - 如何通过 ForeignKey 表选择一个具有第二个顺序和范围的表?
- r - 给定一个数字列表,编写一个函数,给出最大间隔及其大小。前任。2, 4, 9, 左=4, 右=9 间隔=5
- javascript - 带有打字稿的 vscode 调试器:什么决定了对象的呈现方式?
- nextflow - Nexflow:带有文件的结构化输入
- haskell - Haskell:比较序列并计算常见前缀的长度