如何在React Native中从Firebase获取用户ID?

时间:2019-04-12 22:10:03

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

我需要您的帮助,我正在为我的应用程序使用Firebase。我正在尝试获取用户ID,而不是登录用户或我拥有的所有用户。我想像在每个用户的警报中一样显示其(uid)。另外,我将它们显示在平面列表中,并且在警报中设置item.uid时会显示(undefined)。但是,可以正确显示用户的所有其他数据。这是我到目前为止所做的:

** users.js **

export default class usersList extends React.Component{

  state = {
    loading: false,
    uid: '',
    users: [],
    items: []
   };

   componentDidMount() {
        let itemsRef = f.database().ref('users').once('value').then(snapshot => {
               var data = snapshot.val();
               var items = Object.values(data);
               this.setState({items});
               console.log(snapshot.val())

            });
       }


  renderItem({item}) {
    return (
       <View key={index} style={{width: '100%', overflow:'hidden', marginBottom: 5, justifyContent:'space-between', borderBottomWidth:1, borderColor: 'grey'}}>
          <View>
          <View style={{padding:5, width:'100%', flexDirection: 'row', justifyContent: 'space-between'}}>

              <Text>{item.email}</Text>

          </View>
          </View>
        </View>
      )
  }

  render() {
   return (

     <View style={styles.container}>
     <ScrollView>
                {
                    this.state.items.length > 0
                    ? <ItemComponent items={this.state.items} navigation={this.props.navigation} />
                    : <Text>No stores</Text>
                }
                </ScrollView>
            </View>

  );
 }
 }

// ItemComponent.js

export default class ItemComponent extends Component {

  static propTypes = {
      items: PropTypes.array.isRequired
  };

  render() {
    return (
      <View style={styles.itemsList}>
        {this.props.items.map((item, index) => {
            return (
                <View key={index}>
                <TouchableOpacity
                onPress={ () => alert(item.uid)}>
                    <Text style={styles.itemtext}>{item.email}</Text>
                    </TouchableOpacity>
                </View>
            )
        })}
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

firebase.database().ref('user').on('value', (datasnapshot) => {
    this.setState({
       _id: datasnapshot.key
     });`