javascript - 在 react native 应用程序中保留 Firebase 数据

标签 javascript android firebase react-native

我正在尝试在react-native上构建我的第一个应用程序,但我遇到了问题。我想显示来自 firebase 的数据,并且当我重新加载应用程序时插入到 firebase 的数据不会被删除。这就是我的渲染中的内容:

 let tags = this.state.tagArray.map((val, key) => {
  return <TagContainer key={key} keyval={key} val={val}
    deleteMethod={() => this.deleteTag(key)} />
});

这是我的 firebase 配置:

this.itemRef=this.getRef().child('tags');
getRef(){
  return firebaseApp.database().ref();
}

getItems(itemRef){
  itemRef.on('value',(snap)=>{
    let items=[];
    snap.forEach((child) => {
      items.push({
        title:child.val().title,
        _key:child.key
      });   
    });
 Array.prototype.push.apply(this.state.tagArray, items);
  this.setState({ tagArray: this.state.tagArray })
  });

这是我设置 tagArray 的 addtag 函数:

addTag() {
  if (this.state.tagText) {
    this.state.tagArray.push({
      'tag': this.state.tagText
    });
    this.setState({ tagArray: this.state.tagArray })
    this.setState({ tagText: '' })
    this.itemRef.push({title:this.state.tagText});
  }
}

最佳答案

您不应该将数据推送到状态对象中。如果不使用 setState(),则不允许更改状态。

addTag() {
  if (this.state.tagText) {

      let tagArray = [...this.state.tagArray,{'tag': this.state.tagText}]
      this.setState({ tagArray: tagArray,tagText: '' }, ()=>{
          this.itemRef.push({title:this.state.tagText});
      })
  }
}

关于javascript - 在 react native 应用程序中保留 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50186709/

相关文章:

javascript - 使用 JavaScript 查找图像的宽度,同时在 css 中将图像添加为背景图像

javascript - 如何在 html 中从本地 JSON 中搜索元素名称/ID?

javascript - javascript 中的 Socket.io 给出 NOT_RESOLVED 错误

android - 如何在发布版本中使用 Zebra EMDK?

android - 通过单击通知调用 Firebase onMessageReceived

火力地堡 : How to secure content sent without login?

firebase - 架构armv7的 undefined symbol : "_OBJC_CLASS_$_FIRApp"

javascript - 为什么 setter 方法对我的 JavaScript 对象中的其他变量没有任何影响?

java - jpeg 字节到十六进制值

firebase - 如何避免在 firebase ML Kit 的人脸检测 API 中捕获图像模糊