首页 > 解决方案 > React JS:通过另一个对象数组过滤一个对象数组。如何顺序执行四个功能,包括。几个 API 调用

问题描述

目标是通过另一个对象数组过滤一个对象数组。每个数组来自不同的来源。

以下设置可能看起来很奇怪,但不幸的是,这里有几个未提及的原因是必要的。

到目前为止,以下是我的解决方案。不幸的是,我无法按顺序执行这些函数,因此在调用 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;

标签: javascriptarraysreactjsfilteringsequential

解决方案


我建议像这样修改:

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.useridsPromise,并从其中创建了一个 Promise,当所有 fetch 完成时将解析Promise.all

然后我们在位于的初始 Promise 链中返回它componentDidMount。这告诉链在继续之前等待该 Promise 的结果(该 Promise 是 的结果this.fetchJSONFiles)完成,在这种情况下,这将涉及执行finally回调。


现在,还有一些其他的考虑要……考虑。也就是说,如果其中一个fetchJSONFiles调用出现错误会发生什么?这是您必须考虑的事情,但是这些更改应该会让您启动并运行到您想去的地方。


推荐阅读