简体   繁体   English

无法在 setState() 之后将反应状态传递给孩子?

[英]cant pass react state to a child after setState()?

I'm working on reactjs project我正在做 reactjs 项目

where I fetching data from firestore and set the app.js state to the fetched data, and I pass this state to a child of app.js to display it but it's undefined at first then it consoles the right state.我从 firestore 获取数据并将 app.js 状态设置为获取的数据,然后将此状态传递给 app.js 的子级以显示它,但它起初未定义,然后它会控制正确的状态。

How can I make the child component render only after its props is correct?!如何让子组件仅在其 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'))
    })
  }

You can use a concept called " Conditional Rendering ".您可以使用称为“条件渲染”的概念。

It will be like它会像

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

Then, your child component will be rendered only when the state has array data.然后,只有当状态具有数组数据时才会呈现您的子组件。

Similarly, your child component will have props called fetchedItems with full data.同样,您的子组件将具有名为 fetchedItems 的道具,其中包含完整数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM