首页 > 解决方案 > 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 访问状态。我将如何做?

标签: firebasereact-nativeredux

解决方案


要定义一个 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>;
    }
}

推荐阅读