【问题标题】:Trying to list user favourities from API, getting "TypeError: null is not an object (evaluating 'firebase.auth().currentUser.uid')试图从 API 中列出用户的最爱,得到“TypeError: null is not an object (evalating 'firebase.auth().currentUser.uid')
【发布时间】:2019-06-01 22:13:57
【问题描述】:

我正在创建一个连接到 API 并允许用户将从 API 接收到的对象添加到其收藏夹的应用程序(React Native)。我已关注此tutorial,但收到黄色警告“可能未处理的 Promise Rejsction (id:0): TypeError: null is not an object (evalating 'firebase.auth().currentUser.uid')。数据正在添加到数据库,但它没有在我的应用程序中列出(显示)。

Home.js(我希望在其中列出我的最爱)

import * as firebase from 'firebase';
import {Container, Content, ListItem} from 'native-base';

var data = []
var currentUser

class Home extends React.Component {

constructor(props){
   super(props)

    this.ds = new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !==r2})

    this.state = {
        listViewData : data
    }
}
componentDidMount(){

    this.getPlants()
}

getPlants = async()=>{

    currentUser = await firebase.auth().currentUser

    var that = this

    firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

        var newData = [...that.state.listViewData]
        newData.push(data)

        that.setState({ listViewData: newData})
    })
}
render(){
 return(
<Container style={{ flex: 1, backgroundColor: 'yellow'}}>
                <Content>
                    <ListView
                        enableEmptySections
                        dataSource = {this.ds.cloneWithRows(this.state.listViewData)}
                        renderRow={data =>

                            <ListItem>
                                <Text> {data.val().namePlant}</Text>
                            </ListItem>
                        }
                    />
                </Content>
            </Container>
     );}
}

export default Home;

App.js

import * as firebase from 'firebase';
firebase.auth().signInWithEmailAndPassword("mail@gmail.com","password")

...

export default class App extends Component {

  constructor (props) {
super(props);

    if (!firebase.apps.length) { firebase.initializeApp(config.FirebaseConfig); }
}
  render() {

    return <AppContainer  />;
  }
}

Plant.js(从 API 打印特定对象的打印数据并将其添加到数据库)

import * as firebase from 'firebase';

var currentUser
class CatalogPlant extends React.Component {

  addToFavourites = async(scname) =>{

//get current user
currentUser = await firebase.auth().currentUser

//get unique key
var databaseRef = await firebase.database().ref(currentUser.uid).child('plantList').push()

//update plant name at the unique key
databaseRef.set({
  'namePlant': scname

})


  }

// part of code which connects to API and gets the data...

【问题讨论】:

标签: javascript firebase react-native


【解决方案1】:

您的用户似乎尚未登录该应用。在这种情况下,firebase.auth().currentUsernull,所以当您执行firebase.auth().currentUser.uid 时,您是在对null 调用uid

解决此问题的简单方法是在调用firebase.auth().currentUser 后始终检查null。所以:

currentUser = firebase.auth().currentUser

if (currentUser != null) {
    var that = this

    firebase.database().ref(user.uid).child('plantList').on('child_added',function(data){

    ...

请注意,我还从 firebase.auth().currentUser 之前删除了 await。由于firebase.auth().currentUser 不是异步操作,所以这里不需要(也不使用)await

更好的解决方案是使用身份验证状态侦听器,如 RNFirebase documentation 中的此示例所示:

componentDidMount() {
  this.unsubscriber = firebase.auth().onAuthStateChanged((user) => {
    this.setState({ user });
  });
}

所以在你的情况下,这将转化为:

componentDidMount(){
  firebase.auth().onAuthStateChanged((user) => {

    if (user != null) {
      var that = this

       firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

          var newData = [...that.state.listViewData]
          newData.push(data)

          that.setState({ listViewData: newData})
      })
    }
  })
}

在应用重新启动时登录或恢复身份验证状态是异步操作。因此,简单地调用firebase.auth().currentUser 可能会错过用户登录的事实。通过使用onAuthStateChanged,Firebase 将在身份验证状态更改时调用您的代码,这是执行依赖于身份验证状态的事情的最佳时机,例如(在您的情况下)侦听该用户的数据)。

【讨论】:

  • 感谢您的回答!我已经用你的代码替换了我的代码,但现在我收到一个红色错误“未定义不是对象(正在评估'currentUser.uid'”。
  • 是的,这是我的代码中的复制/粘贴错误。我在答案中修复了它。
猜你喜欢
  • 2020-08-15
  • 2021-06-16
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多