首页 > 解决方案 > 反应组件中的状态不会呈现

问题描述

我的反应组件根本不会从状态加载数据。我的加载功能和它的渲染一样工作,但是,即使状态更新(我记录了它,它确实返回了预期的数据)与渲染无关。如果帖子为空,则<p>nothing</>标签不显示,如果有数据,则不会打印在 p 标签中,也不会加载到我的轮播中。

import React, { Component } from 'react';
import { withFirebase } from '../Firebase';
import AliceCarousel from 'react-alice-carousel';
import 'react-alice-carousel/lib/alice-carousel.css';

import PostItem from '../Market/PostItem';

class LandingPosts extends Component {
  constructor(props) {
    super(props);

    this.state = {
      text: '',
      loading: false,
      posts: [],
      limit: 5,
    };

  }

  componentDidMount() {
    this.onListenForMessages();
  }

  onListenForMessages = () => {
    this.setState({ loading: true });

    this.props.firebase
      .collectionGroup('settings')
      .where('homepagepost', '==', true)
      .get().then(snapshot => {

      let posts = [];

      snapshot.forEach(doc => {

        doc.ref.parent.parent.get().then(doc => {
          posts.push({ ...doc.data(), uid: doc.id });
          console.log(posts);
        });

      });

      this.setState({ posts: posts.reverse(), loading: false });

    });
  };


  responsive = {
    0: { items: 1 },
    1024: { items: 3 },
  };

  render() {
    const { loading } = this.state;

    return (
      <div>
        {loading && <div>Loading ...</div>}
        {this.state.posts && (
          <p>{this.state.posts[0]}</p>
        )}
        {!this.state.posts && (
          <p>nothing</p>
        )}
        <AliceCarousel
          items={this.state.posts.map(item => {return <PostItem data={item}/>})}
          responsive={this.responsive}
          autoPlayInterval={2000}
          autoPlayDirection="rtl"
          autoPlay={true}
          fadeOutAnimation={true}
          mouseDragEnabled={true}
          disableAutoPlayOnAction={true}
          buttonsDisabled={true}
        />
      </div>
    );
  }
}

export default withFirebase(LandingPosts);

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


我认为,在您的情况下,以下代码是异步的。

doc.ref.parent.parent.get().then(doc => {
    posts.push({ ...doc.data(), uid: doc.id });
    console.log(posts);
});

如果是这样,请尝试在 then 中添加设置状态或创建这样的承诺数组。

posts.push(
 doc.ref.parent.parent.get().then(doc => {
    posts.push({ ...doc.data(), uid: doc.id });
    console.log(posts);
 });
)
Promise.all(posts).then((_posts)=>this.setState({ posts: _posts.reverse(), loading: false });)

推荐阅读