2016-11-20 50 views
2

我已經寫了一個基本的反應 + Firebase應用程序只是爲了確定它是如何工作的。React組件不在firebase child_update事件上重新呈現

我有返回基於從火力地堡數據庫中的組數據返回反應的組分(郵政)的列表的反應組分(ViewPosts)。

我已經附加child_removed的火力地堡事件,child_addedcomponentDidMount()

child_changed所有這一切我安裝工作正常的事件,但只有child_changed事件不重新渲染頁面。但我添加了一個console.log只是爲了檢查事件是否被觸發。 (我正在更新/刪除使用Firebase控制檯的值)

我認爲這可能是一個關鍵的問題,所以我甚至添加了一個索引,使其獨特但仍然沒有幸運。我在這裏錯過了什麼?爲什麼代碼給了我這種行爲。

由於React只更新更新的組件,即使我刪除了或向列表中添加了新組件,列表也不會更新,但是如果我刪除了一個組件並且該組件恰好位於更新組件之上(Post)那麼由於React被迫重新呈現該組件下方的列表,我可以看到更新後的值。

請幫我找出爲什麼發生這種情況

ViewPosts

import React, { Component } from 'react'; 
import * as firebase from 'firebase'; 
import Post from './Post'; 

var listItems = null; 
var starCountRef = null; 
class ViewPosts extends Component { 

    constructor(props) { 
    super(props); 
    this.state = {renderedList: []}; 
    this.getDatafromDB = this.getDatafromDB.bind(this); 
    starCountRef = firebase.database().ref('posts'); 
    } 

    getDatafromDB() { 
    listItems = []; 
    starCountRef.once('value', snapshot => { 
     var results = snapshot.val(); 
     var resultsKeys = Object.keys(results); 
     listItems = resultsKeys.map((key,i) => <Post key={key.toString() + i} value={results[key].value + i } />); 

     this.setState({ 
     renderedList : listItems 
     }); 
    }); 
    } 
    componentDidMount(){ 

    // Get the data on a post that has been removed 
    starCountRef.on("child_removed", snapshot => { 
     var deletedPost = snapshot.val(); 
     console.log("The post valued '" + deletedPost.value + "' has been deleted"); 
     this.getDatafromDB(); 
    }); 

    // Get the data on a post that has been removed 
    starCountRef.on("child_added", snapshot => { 
     var addedPost = snapshot.val(); 
     console.log("The post value '" + addedPost.value + "' has been added"); 
     this.getDatafromDB(); 
    }); 

    starCountRef.on("child_changed", snapshot => { 
     var changedPost = snapshot.val(); 
     console.log("The updated post value is " + changedPost.value); 
     this.getDatafromDB(); 
     console.log("this.state.listItems " + this.state.renderedList); 
    }); 

    } 
    render() { 
    return(
    <div> 
     <ul> 
     {this.state.renderedList} 
     </ul> 
     </div> 
    ); 
} 
} 

export default ViewPosts; 

import React, { Component } from 'react'; 

class Post extends Component { 

    constructor(props) { 
    super(props); 
    this.state = {value: props.value}; 
    } 

render() { 
    return(
    <li>{this.state.value}</li> 
    ); 
} 
} 

export default Post; 

回答

0

我介紹了一個新的屬性 「UID」,並繪製了UID來組件的關鍵。 然後,當我更新UID和值時,React將其作爲更新選取並重新呈現該組件。

即使我已經將索引包含在鍵中,直到刪除上面的一個組件將會是相同的,並解釋了爲什麼當我從頂部刪除組件時重新呈現的原因。

基本上,如果有多個相同類型的組件,那麼這些組件必須與唯一鍵綁定,除非該鍵已更改,即使該值發生更改,React也不會重新呈現該組件。

據我所知,React在後臺做了什麼,創建一個虛擬DOM並將其與現有的DOM進行比較,並只重新渲染更改後的組件。似乎這樣看起來的關鍵,如果有多個時,像,如果它同它跳過了整個組件

而且在情況下,如果你不知道如何創建我使用lodash的_.uniqueId([prefix=''])方法生成一個關鍵

謝謝,

相關問題