我的反应组件根本不会从状态加载数据。我的加载函数和它的渲染一样按预期工作,但是,即使状态更新(我记录了它,它确实返回了预期的数据)与渲染无关。如果帖子是空的,<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 回答
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
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 });)
添加回答
举报
0/150
提交
取消