如何返回带有数据的组件?

时间:2019-01-16 19:43:32

标签: javascript reactjs firebase

我正在尝试列出需要具有Firebase云存储内容的div列表。但是我不知道如何执行从firebase中获取数据并返回MyNotes数据的代码。

看到这个:

class HandleMyNotes extends Component {
  componentDidMount() {
    const db = firebase.firestore();

    db.collection("posts")
      .where("author.email", "==", this.props.authorEmail)
      .get()
      .then(querySnapshot => {
        querySnapshot.map(doc => {
          return <MyNotes data={doc.data()} key={doc.id} />;
        });
      })
      .catch(() => {
        alert("An error was happend");
      });
  }

  render() {
    return <MyNotes />;
  }
}

这有效,但不返回数据,并且,如果我尝试将数据放入render(){},则不起作用,因为也许我没有返回MyNotes

我该怎么办?

这就是我console.log(querySnapshot)

时收到的数据
QuerySnapshot
docs: (...)
empty: (...)
metadata: SnapshotMetadata {hasPendingWrites: false, fromCache: false}
query: (...)
size: (...)
_cachedChanges: null
_cachedChangesIncludeMetadataChanges: null
_firestore: Firestore {_queue: AsyncQueue, INTERNAL: {…}, _config: FirestoreConfig, _databaseId: DatabaseId, _dataConverter: UserDataConverter, …}
_originalQuery: Query {path: ResourcePath, explicitOrderBy: Array(0), filters: Array(1), limit: null, startAt: null, …}
_snapshot: ViewSnapshot {query: Query, docs: DocumentSet, oldDocs: DocumentSet, docChanges: Array(1), mutatedKeys: SortedSet, …}
__proto__: Object

2 个答案:

答案 0 :(得分:0)

您不应从生命周期方法中返回组件。 将api数据设置为本地状态,然后将其传递给render函数中的组件。

componentDidMount() {
  const db = firebase.firestore();

  db.collection("posts")
    ...
    .then(querySnapshot => {
      this.setState({ data: querySnapshot })
    })
    ...
  }

  render() {
    return <MyNotes data={this.state.data} />;
  }

答案 1 :(得分:0)

class HandleMyNotes extends Component {
  state = {
    isLoading: false,
    err: null,
    posts: [],
  };

  componentDidMount() {
    const db = firebase.firestore();

    this.setState({
     isLoading: true,
    });

    db.collection("posts")
      .where("author.email", "==", this.props.authorEmail)
      .get()
      .then(querySnapshot => {
        this.setState({
         isLoading: false,
         posts: querySnapshot.map(note => note.data()),
        });
      })
      .catch(err => {
        this.setState({
         isLoading: false,
         err,
        });
      });
  }

  render() {
    const {
      isLoading,
      err,
      notes,
    } = this.state;
    // if loading or error you can handle here.
    return (
      <div>
        {notes.map(note => <Note key={note.id} data={note}/>)}
      </div>
    );
  }
}