我正在尝试设置项目的状态,然后将新状态用作传递给我的组件的道具,但它似乎没有及时设置状态
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}/>
这是因为在渲染AddToCartRow
时,this.state.cartKey
是null
。
您正在从尚未实现的承诺.then(..)
中设置cartKey
。
您的render()
实际上是在您的constructor
填充this.state.cartKey
之前呼叫的。
您可以编写以下逻辑,以仅在this.state.cartKey
计算结果为 true 时呈现组件,并且正如我们所知,null
计算结果为 false
.
{this.state.cartKey && <AddToCartRow item={this.props.data.sizes} option='size' key={this.state.cartKey}/>}