【问题标题】:Cannot setState Variable无法设置状态变量
【发布时间】:2017-03-24 00:07:28
【问题描述】:

我使用 setState 来更新程序中的 2 个状态。我的 console.log 能够显示 2 个更新的状态。但是,setState 方法不起作用。年龄和性别这两个变量保持为空,并且不会在我的 jsx 中呈现。提前感谢您的帮助

this.state={ age: '', gender: '' }........ //this.state provided


  fetchUserProfile(){
const { currentUser } = firebaseApp.auth();
firebaseApp.database().ref(`/users/${currentUser.uid}/profile`).orderByValue()
.on('child_added', snapshot => {
    console.log(snapshot.key, snapshot.val()); //successfully shows age and gender on console
    this.setState({
      age: snapshot.val().age,                 //does not update the state of age and gender
      gender: snapshot.val().gender
    })
})

}

【问题讨论】:

    标签: firebase react-native firebase-realtime-database


    【解决方案1】:

    您是否绑定了 fetchUserProfile 函数?

    如果不只是改变:

    fetchUserProfile(){fetchUserProfile = () => {

    【讨论】:

    • 嗨,马特,我尝试将绑定函数添加到构造函数,但它不起作用。我也尝试过 fetchUserProfile=()=> 但也没有成功。 constructor(){ super() this.state={ name: '', mobile: '', email: '', date: '', age: '', gender: '' }, this.fetchUserProfile = this.fetchUserProfile .bind(this) }
    • 为了测试它是否工作,如果你改变 setState 中的年龄和性别来喜欢年龄:10,性别:'男'。有用吗?
    • 嗨,马特,当我将 setState 方法中的年龄和性别更改为年龄:10 和性别:“男性”时,它仍然不起作用。
    猜你喜欢
    • 2021-03-16
    • 2021-07-11
    • 2019-07-31
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多