基本firebase组件无法在视图重新加载时卸载

时间:2018-03-04 20:04:49

标签: reactjs firebase firebase-realtime-database

当用户加载不同的视图(替换显示Firebase信息的用户信息中心)时,一切都很好。

但是当用户返回用户仪表板视图时,会抛出错误并且页面上没有任何内容呈现。

错误warning.js?0f60:33 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

整个组件:

// register user component

import ...

const provider = new firebase.auth.GoogleAuthProvider();
const auth = firebase.auth();

class Registration extends Component {

    constructor() {
        super();
        this.state = {
            vendorName: '',
            vendorType: '',
            items: [],
            user: null
        }
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.login = this.login.bind(this);
        this.logout = this.logout.bind(this);
    }

    ...

    componentDidMount() {
        // check if user is logged in
        auth.onAuthStateChanged((user) => {
            if(user) {
                this.setState({user});
            }
        });
        // retrieve data
        const itemsRef = firebase.database().ref('vendors');
        itemsRef.on('value', (snapshot) => {
            let items = snapshot.val();
            let newState = [];
            for (let item in items) {
                newState.push({
                    id: item,
                    vendorName: items[item].vendorName,
                    vendorType: items[item].vendorType
                });
            }
            this.setState({
                items: newState
            });
        });
    }
     componentWillUnmount() {
     this.firebase.off();
     }

1 个答案:

答案 0 :(得分:2)

您正在尝试从数据库off(),但您应该在ref上执行此操作。

this.itemsRef = firebase.database().ref('vendors');
this.itemsRef.on('value', this.someCallback);

//.....

componentWillUnmount() {
  this.itemsRef.off('value', this.someCallback);
}

From Firebase API for Reference

  

如果未指定回调,则指定所有回调   eventType将被删除。同样,如果没有eventType或回调   指定后,参考的所有回调都将被删除。

示例

var onValueChange = function(dataSnapshot) {  ... };
ref.on('value', onValueChange);
// Sometime later...
ref.off('value', onValueChange);