使用状态时在 React Native 中出现未定义的对象错误?

Getting an undefined object error in react native while using state?

我遇到错误 "undefined is not an object(evaluating "this.state.user") 通过按钮调用登录功能时。 this.state.user 的值来自于 onchangeText 方法。请帮忙。 该函数位于 firebase 值事件中。

constructor(props) {
    super(props);
    this.state = { user: '', password: '' };
}

login = () => {
    db.ref('admins/').once('value', function(snapshot) {
        var user = snapshot.child('user_1').val();
        if (this.state.user == user) {
            this.props.navigation.navigate('FACULTYUI');
        }
    });
};

改变这个:

db.ref('admins/').once('value', function(snapshot) {

进入这个:

db.ref('admins/').once('value', ((snapshot) => {

使用使用词法作用域的箭头函数,这意味着在function外定义的变量在function内也是一样的。

来自 docs:

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.