反应组件中的状态不会呈现

我的反应组件根本不会从状态加载数据。我的加载函数和它的渲染一样按预期工作,但是,即使状态更新(我记录了它,它确实返回了预期的数据)与渲染无关。如果帖子是空的,<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);



ITMISS
浏览 144回答 2
2回答

12345678_0001

我认为,在您的情况下,以下代码是异步的。doc.ref.parent.parent.get().then(doc => {&nbsp; &nbsp; posts.push({ ...doc.data(), uid: doc.id });&nbsp; &nbsp; console.log(posts);});如果是这样,请尝试在 then 中添加设置状态或创建这样的承诺数组。posts.push(&nbsp;doc.ref.parent.parent.get().then(doc => {&nbsp; &nbsp; posts.push({ ...doc.data(), uid: doc.id });&nbsp; &nbsp; console.log(posts);&nbsp;});)Promise.all(posts).then((_posts)=>this.setState({ posts: _posts.reverse(), loading: false });)

浮云间

我认为您必须在渲染中“重复”您的状态声明。像这样:const { 文本、加载、帖子、限制 } = this.state至少我的组件中是这样的
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript