2017-05-25 173 views
0

我想設置一個項的狀態,然後使用新的狀態,這是傳遞給我的組件的道具,但它不會出現要及時設置狀態返回null陣營本地國有

constructor (props) { 
    super(props) 
    this.cartFirebase = firebaseApp.database().ref('carts') 
    this.cartFirebase.child(DeviceInfo.getUniqueID() + '/items').push({ 
     item: this.props.data.name, 
     qty: 1 
    }).then((snap) => { 
     this.state = { 
     cartKey: snap.key 
     } 
    }) 
    } 

組件

<AddToCartRow item={this.props.data.sizes} option='size' key={this.state.cartKey}/> 

回答

1

這是因爲在渲染AddToCartRow的時間,this.state.cartKeynull

您正在設置cartKey從Promise .then(..)尚未實現。

您的render()實際上是在您的constructor已填充之前調用。

您可以編寫以下邏輯以僅在this.state.cartKey的計算結果爲true時渲染組件,並且正如我們所知,null的計算結果爲false

{this.state.cartKey && <AddToCartRow item={this.props.data.sizes} option='size' key={this.state.cartKey}/>}