javascript - 反应组件中的状态不会呈现
问题描述
我的反应组件根本不会从状态加载数据。我的加载功能和它的渲染一样工作,但是,即使状态更新(我记录了它,它确实返回了预期的数据)与渲染无关。如果帖子为空,则<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);
解决方案
我认为,在您的情况下,以下代码是异步的。
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 });)
推荐阅读
- reactjs - react 说 Error: Invalid hook call when I try to use material makestyles
- sql - 使用数据库链接时在多个条件下进行内连接
- android - 保存片段状态导航组件JAVA
- python - Python Selenium - 数据不可见;没有错误
- javascript - 画布上下文上的多个填充():rgba透明颜色改变
- excel - Excel 动态数组 - 可能的错误?
- javascript - 不随页面刷新的计数器
- swiftui - SwiftUI 从 UITextField 中关闭键盘
- image - 如何将图像添加到 Go 中的特定文件夹中?收到类似错误:`%!(EXTRA *fs.PathError=open /photos: read-only file system)`
- html - 即使我已经很好地计算了网格系统(引导程序),列也不会粘在一起