【问题标题】:cant pass react state to a child after setState()?在 setState() 之后不能将反应状态传递给孩子吗?
【发布时间】:2021-01-23 17:28:05
【问题描述】:

我正在做 reactjs 项目

我从 firestore 获取数据并将 app.js 状态设置为获取的数据,然后将此状态传递给 app.js 的子级以显示它,但它一开始是未定义的,然后它控制正确的状态。

如何让子组件只有在 props 正确后才渲染?!

  fetchDataFromFirestore = async () => {
    let dataRefFromFirestore = database.doc('items/fruitsDataJsonFile');
    (await dataRefFromFirestore).onSnapshot((snapshot) => {
      let fetchedItems = snapshot.data();
      this.setState({
        fetchedItems: fetchedItems.data
      },
        console.log('DONEEE ADIING'))
    })
  }

【问题讨论】:

  • 在子组件中渲染条件return(props.data?(<div>whatever </div>):null)

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

您可以使用一个名为“条件渲染”的概念。

会是这样的

    {!!this.state.fetchedItems?.length && 
<YourChildComponent fetchedItems={this.state.fetchedItems}>

那么,你的子组件只有在状态有数组数据时才会被渲染。

同样,您的子组件将拥有名为 fetchedItems 的具有完整数据的道具。

参考:https://reactjs.org/docs/conditional-rendering.html

【讨论】:

  • 在您的代码中,如果length0,那么它将在屏幕上呈现0
  • @azium ,感谢您指出,我通常的不-不!哈哈 。刚刚添加。干杯!
猜你喜欢
  • 2020-04-06
  • 1970-01-01
  • 2017-08-22
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多