如何从Firebase实时数据库中提取密钥并传递到编辑屏幕?

时间:2020-04-17 19:46:14

标签: firebase react-native

我是本机/ Firebase的新手,我想弄清楚如何从数据库中的条目中获取唯一密钥(使用Push时,它们是随机生成的),所以我可以更新数据库中的条目编辑画面。非常感谢您提供有关如何实现此目标的帮助或指导。

这是我的主供稿屏幕,其中抓取并显示了数据库中的所有项目:

let ref = db.ref('dogs');

export default class Main extends React.Component {
  _isMounted = false;
  constructor() {
    super();
    this.state = {
      currentUser: null,
      errorMessage: null,
      items: [],
      key: '',
    };
  }
  componentDidMount() {
    this._isMounted = true;

    const {currentUser} = firebaseAuth;

    this.setState({currentUser});
    ref.on('value', snapshot => {
      if (this._isMounted) {
        let data = snapshot.val();
        let items = Object.values(data);
        this.setState({items});
      }
    });
  }
  componentWillUnmount() {
    this._isMounted = false;
  }


  render() {
    const {currentUser} = this.state;
    return (
      <View style={styles.container}>
        <View>
          <View style={styles.container}>
            {this.state.items.length > 0 ? (
              <ItemComponent
                style={styles.listDog}
                items={this.state.items}
                navigation={this.props.navigation}
              />
           ) : (
              <Text>No dogs</Text>
            )}
          </View>
          <View style={styles.bottomContainer}>
            <TouchableOpacity
              style={styles.addBtn}
              onPress={() => this.props.navigation.navigate('dogCreation')}>
              <View>
                <FontAwesomeIcon style={styles.penIcon} icon={faBone} />
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}

这是我的物品组件:

export default class ItemComponent extends Component {
  static propTypes = {
    items: PropTypes.array.isRequired,
  };

  render() {
    return (
      <View style={styles.itemsList}>
        {this.props.items.map((item, dog) => {
          return (
            <TouchableOpacity
              key={dog}
              onPress={() =>
                this.props.navigation.navigate('Profile', {
                  name: item.name,
                  image_uri: item.image_uri,
                  parent: item.parent,
                  parentEmail: item.parentEmail,
                  parentTwo: item.parentTwo,
                  parentTwoEmail: item.parentTwoEmail,
                })
              }>
              <View style={styles.dogCard}>
                <Image source={{uri: item.image_uri}} style={styles.dogImage} />
                <Text style={styles.itemtext}>{item.name} </Text>

                <FontAwesomeIcon style={styles.chevron} icon={faChevronRight} />
              </View>
            </TouchableOpacity>
          );
        })}
      </View>
    );
  }
}

这是我的个人资料页面:

export default class Profile extends React.Component {
  render() {
    const {navigation} = this.props;
    const dogName = navigation.getParam('name', '');
    const image_uri = navigation.getParam('image_uri', '');
    const parent = navigation.getParam('parent', '');
    const parentEmail = navigation.getParam('parentEmail', '');
    const parentTwo = navigation.getParam('parentTwo', '');
    const parentTwoEmail = navigation.getParam('parentTwoEmail', '');

    return (
      <View style={styles.container}>
        <Image style={styles.dogImage} source={{uri: image_uri}} />
        <View style={styles.contentBlock}>
          <Text style={styles.header}>Name</Text>
          <Text style={styles.textStyle}>{dogName}</Text>
        </View>
        <View style={styles.contentBlock}>
          <Text style={styles.header}>Pet Parent 1 Info</Text>
          <Text style={styles.subHeader}>Name</Text>
          <Text style={styles.textStyle}>{parent}</Text>
          <Text style={styles.subHeader}>Name</Text>
          <Text style={styles.textStyle}>{parentEmail}</Text>
        </View>
        <View style={styles.contentBlock}>
          <Text style={styles.header}>Pet Parent 2 Info</Text>
          <Text style={styles.subHeader}>Name</Text>
          <Text style={styles.textStyle}>{parentTwo}</Text>
          <Text style={styles.subHeader}>Name</Text>
          <Text style={styles.textStyle}>{parentTwoEmail}</Text>
        </View>
        <TouchableOpacity
          style={styles.addBtn}
          onPress={() =>
            this.props.navigation.navigate('editProfile', {
              name: dogName,
              image_uri: image_uri,
              parent: parent,
              parentEmail: parentEmail,
              parentTwo: parentTwo,
              parentTwoEmail: parentTwoEmail,
            })
          }>
          <Text>EDIT</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

这是我的编辑个人资料页面更新功能:

let ref = db.ref('dogs');
let addItem = (
  dog,
  parent,
  parentEmail,
  parentTwo,
  parentTwoEmail,
  image_uri,
) => {
  db.ref('/dogs/')
    .update({
      name: dog,
      parent: parent,
      parentEmail: parentEmail,
      parentTwo: parentTwo,
      parentTwoEmail: parentTwoEmail,
      image_uri: image_uri,
    });
};

1 个答案:

答案 0 :(得分:0)

仅在返回快照返回snapshot.key时使用。

    ref.on('value', snapshot => {
      if (this._isMounted) {
        let id = snapshot.key;
        let data = snapshot.val();
        let items = Object.values(data);
        this.setState({items});
      }
    });

您可以在此处查看更多详细信息:https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#key

**一些要点,如果您直接在react native中使用firebase库,我建议您使用专门为React Native创建的版本,它可以纠正OS中定时器的一些问题。 您可以在这里看到:https://rnfirebase.io/

**其他重要信息,您的firebase返回函数是一个侦听器,而使用this._isMounted是反模式。您可以使用subscriber停止监听器。

所以...

let subscriber;
...
componentDidMount() {

    const {currentUser} = firebaseAuth;

    this.setState({currentUser});

    subscriber = ref.on('value', snapshot => {    
        let data = snapshot.val();
        let items = Object.values(data);
        this.setState({items});
    });
  }

  componentWillUnmount() {
    // Stop listening for updates when no longer required
    this.subscriber();
  }