【问题标题】:listen for changes firebase react native监听变化 firebase react native
【发布时间】:2017-07-13 21:57:35
【问题描述】:

我想显示点赞数。 如何收听和显示值变化?

在 firebase 文档中,他们说要使用 .on('value', function (snap))。但是如何实施呢?我应该创建一个新功能吗?状态呢?非常感谢!

class WordItem extends Component {

constructor(props) {
super(props);
this.onPressIcon = this.onPressIcon.bind(this);
this.state = {
  dataSource: new ListView.DataSource({
  rowHasChanged: (row1, row2) => row1 !== row2,
    }),
  }
}



onPressIcon(word){

                var config = {
                apiKey: "",
                authDomain: "",
                databaseURL: ""
                };

                    var ref = firebase.database().ref();

                    let childItem = word+"/likes";
                    console.log(childItem, "childItem")

                    var likes_words = ref.child("items").child(word).child("likes");


                    likes_words.transaction(function(currentLike) {
                        return currentLike + 1;
                        });

            // Sync Object Changes
            likes_words.on('value', function (snap){
              ???
            });

  }

【问题讨论】:

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


    【解决方案1】:
    likes_words.on('value', snapshot => {
          value_of_likes = snapshot.val() 
    });
    

    在 value_of_likes 中,您将获得总点赞数,如果您正在使用 redux,您可以发送调度操作,或者您可以调用任何其他函数来更新您的状态

    【讨论】:

    • 好吧,它给了我总喜欢,但我如何在 render() 中使用它? this.setState({ dataSource: this.state.dataSource.cloneWithRows(value_of_likes) }); console.log(value_of_likes)
    • this.state = { value_of_likes: 0 };componentWillMount() { this.createDataSource(this.state.value_of_likes); }createDataSource(value_of_likes) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(value_of_likes); }render() { return ( <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} /> ); }likes_words.on('value', snapshot => { value_of_likes = snapshot.val() this.setState({ value_of_likes }); });
    • 您可以初始化 value_of_likes。然后在 this.dataSource = ds.cloneWithRows(value_of_likes); 中传递喜欢的值在渲染方法中,使用此数据源创建 ListView。当新的 value_of_likes 出现时,更新状态。
    • 快到了!我不知道将 likes_words.on 放在哪里。如果在 onPressIcon 函数内部,我可以在日志中看到它还会增加渲染的次数,如下所示:200、201、201、202、202、202
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多