反应本机为状态返回 null

React native returning null for state

我正在尝试设置项目的状态,然后将新状态用作传递给我的组件的道具,但它似乎没有及时设置状态

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}/>

这是因为在渲染时AddToCartRowthis.state.cartKeynull

您正在从尚未实现的承诺 .then(..) 中设置 cartKey

您的 render() 实际上是在您的 constructor 填充 this.state.cartKey 之前呼叫的。

您可以编写以下逻辑以仅在 this.state.cartKey 计算结果为真时渲染组件,而我们知道 null 计算结果为 false.

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