为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

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


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 });)



查看完整回答
反对 回复 2021-11-25
?
浮云间

TA贡献1829条经验 获得超4个赞

我认为您必须在渲染中“重复”您的状态声明。像这样:

const { 文本、加载、帖子、限制 } = this.state

至少我的组件中是这样的


查看完整回答
反对 回复 2021-11-25
  • 2 回答
  • 0 关注
  • 143 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信