javascript - React JS:通过另一个对象数组过滤一个对象数组。如何顺序执行四个功能,包括。几个 API 调用
问题描述
目标是通过另一个对象数组过滤一个对象数组。每个数组来自不同的来源。
以下设置可能看起来很奇怪,但不幸的是,这里有几个未提及的原因是必要的。
- 第一步是从 Firebase 数据库中获取一组对象,其中包含一些(最新)上传的帖子(allposts)的元数据。
- 在第二步中,该数组将针对用户 ID 和文本 ID (filterArrayIds) 进行过滤。
- 在第三步中,对于每个过滤的用户 ID,将调用一个 API 以获取相应用户 ID 的所有现有帖子的详细信息。这些将被合并到一个帖子数组(fetchJSONFiles)中。
- 在第四步中,这个合并的帖子数组应该针对第二步的文本标识数组(filterJSON)中的所有文本标识进行过滤。
到目前为止,以下是我的解决方案。不幸的是,我无法按顺序执行这些函数,因此在调用 filterJSON() 之前,尤其是 fetchJSONfiles() 已完全完成。
我被困在这里几个小时......任何帮助都会受到高度赞赏,并且会让我很开心。谢谢!
示例数据:
allposts: [
{
dateofpost: "1539181118111",
textid: "1",
userid: "Alice",
},
{
dateofpost: "1539181118222",
textid: "3",
userid: "Bob",
},
]
-
allfilteredTexts: [
{
title: "Lorem",
textid: "1",
},
{
title: "Ipsum",
textid: "2",
},
{
title: "Dolor",
textid: "3",
},
]
预期结果:
latestPosts: [
{
title: "Lorem",
textid: "1",
},
{
title: "Dolor",
textid: "3",
},
]
到目前为止我的解决方案:
class Explore extends React.Component {
constructor(props) {
super(props);
this.state = {
allposts: [],
textids: [],
userids: [],
allfilteredTexts: [],
};
}
componentDidMount() {
const allfilteredTexts = {...this.state.allfilteredTexts}
firebase
.firestore()
.collection("allposts")
.orderBy("dateofpost")
.get()
.then(snapshot => {
const allposts = this.state.allposts;
snapshot.forEach(doc => {
allposts.push({
userid: doc.data().userid,
textid: doc.data().textid,
dateofpost: doc.data().dateofpost,
});
});
this.setState({
allposts: allposts,
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
})
.then(() => {
this.filterArrayIds();
})
.then(() => {
this.fetchJSONFiles();
})
.finally(() => {
this.filterJSON();
});
}
filterArrayIds() {
var userids = this.state.userids
var textids = this.state.textids
if (this.state.allposts) {
var filtereduserids = [...new Set([].concat(...this.state.allposts.map(o => o.userid)))];
var filteredtextids = [...new Set([].concat(...this.state.allposts.map(p => p.textid)))];
this.setState({
userids: filtereduserids,
textids: filteredtextids,
})
}
}
fetchJSONFiles() {
if (this.state.userids) {
this.state.userids.forEach((username) => {
var filteredTexts = []
const options = {username} //here would be more API options //
getFile(options)
.then((file) => {
filteredTexts = JSON.parse(file || '[]');
})
.then (() => {
Array.prototype.push.apply(filteredTexts, this.state.allfilteredTexts);
this.setState({
allfilteredTexts: filteredTexts,
})
})
}
}
filterJSON(){
let latestPosts = (this.state.allfilteredTexts.filter(
(el) => { return el.id.indexOf(this.state.textids) !== -1;
}));
}
render () {
return (
<div>
<Switch>
<Route
path='/explore/latest/'
render={(props) => <ExploreLatest {...props} allposts={this.state.allposts} allfilteredTexts={this.state.allfilteredTexts} />}
/>
</Switch>
</div>
)
}
}
export default Explore;
解决方案
我建议像这样修改:
fetchJSONFiles() {
if (this.state.userids) {
return Promise.all(this.state.userids.map((username) => {
var filteredTexts = []
const options = {username} //here would be more API options //
return getFile(options)
.then((file) => {
filteredTexts = JSON.parse(file || '[]');
})
.then (() => {
Array.prototype.push.apply(filteredTexts, this.state.allfilteredTexts);
this.setState({
allfilteredTexts: filteredTexts,
})
}))
}
}
那么这些行:
.then(() => {
this.fetchJSONFiles();
})
可以变成:
.then(() => {
return this.fetchJSONFiles();
})
为什么?
之所以fetchJSONFiles
没有在 Promise 链的其余部分之前完成是因为 Promise 链不知道要等待fetchJSONFiles
. fetchJSONFiles
进行异步调用,因此其余的同步代码继续执行。
但是,通过从 fetchJSONFiles 返回一个 Promise,我们可以“等待”一些东西。这使用了该功能Promise.all
,它基本上说“创建一个在此承诺数组中的每个承诺完成时完成的承诺”。
而不是forEach
我们使用map
, 因为这允许我们基于基本数组创建一个新数组,而不是仅仅循环它。getFile
然后我们返回 Promise 链,而不是仅仅调用。因此,我们从 中创建了一组this.state.userids
Promise,并从其中创建了一个 Promise,当所有 fetch 完成时将解析Promise.all
。
然后我们在位于的初始 Promise 链中返回它componentDidMount
。这告诉链在继续之前等待该 Promise 的结果(该 Promise 是 的结果this.fetchJSONFiles
)完成,在这种情况下,这将涉及执行finally
回调。
现在,还有一些其他的考虑要……考虑。也就是说,如果其中一个fetchJSONFiles
调用出现错误会发生什么?这是您必须考虑的事情,但是这些更改应该会让您启动并运行到您想去的地方。
推荐阅读
- java - 使用 Collections.sort() 对 ArrayList 进行复杂排序?
- c# - Unity3D蓝牙串行馈送分配器问题C#
- rust - Rust 中的无符号整数溢出
- javascript - 使用 Firebase 云功能发送通知有困难吗?
- android - 片段 - 无法添加子视图,表示子视图已经有父视图
- python - Yield 关键字返回 0x107e4b3c0 而 Return 函数仅返回列表中的最后一个值
- html5-video - 默认 Html5 视频海报
- mysql - 如何写一个删除命令来替换三个sql?
- android - 在不同的机器上运行时,不变违规反应本机
- laravel - 服务器上的 Laravel 与 ip