首页 > 解决方案 > 将对象数组过滤到新数组中

问题描述

在反应我有:

    state = {
     Producers: [], 
     France: [],
     Spain: [],
     Germany: [],
     Portugal: [],
     Greece: [],
     Austria: [],
     isLoading: false
     };

生产者数组:

     {
    "_id" : ObjectId("5cc0bf1815cc7a2225edab0b"),
    "Code" : "FPG-BCH14",
    "URL" : "/jSQcl",
    "Just_In" : "",
    "Country" : "France",
    "Region" : "Burgundy"
},
{
    "_id" : ObjectId("5cc0bf1815cc7a2225edab0c"),
    "Code" : "FPG-CHA17",
    "URL" : "/XPxx",
    "Just_In" : "",
    "Country" : "France",
    "Region" : "Burgundy"  
},
{
    "_id" : ObjectId("5cc0bf1815cc7a2225edab0d"),
    "Code" : "FPG-BPN16",
    "Just_In" : "",
    "Country" : "France",
    "Region" : "Burgundy"

},

{
    "_id" : ObjectId("5cc0bf1815cc7a2225edab0e"),
    "Code" : "PAP-VIN17",
    "Country" : "Portugal",
    "Region" : "Vinho Verde",
    "Subregion" : "Lima"

}

现在我有所有的对象state.Producers,我想放入任何具有价值的对象state.Producers.Country === "France"(等等所有国家)。

这就是我设置状态的方式:

    loadProducers = () => {

     API.getProducers()
     .then(res => 
     this.setState({Producers: res.data})
     )
     .catch(err => console.log(err));
       }

所以我想.then在为生产者和.filter每个国家设置状态之后我需要另一个声明,但我似乎无法让它发挥作用。

标签: javascriptarraysreactjsfilter

解决方案


React.Component#setState()不返回任何内容,因此 aPromise#then()将有一个未定义的传递给它的回调。为避免这种情况,请改为传递回调,setState()以便它在状态更新后运行,但您应该使用正确的方法并使用生命周期React.Component#componentDidUpdate()。您应该使用生命周期的原因有很多,包括这样您就可以轻松更改数据源的来源,而无需更改状态本身的派生方式,生命周期几乎不需要维护,并且在组件得到更新,这意味着您不会遇到基于赛车异步条件的计时问题。

this.componentDidUpdate = function componentDidUpdate(
  previousProps,
  previousState
) {
  // wrap it in a comparison so that you don't infinitely loop
  if (//compare producers to previous producers here) {
    // they have changed, update state, use updater to prevent timing problems
    this.setState(state => {
      // keep changing data in sync
      // this also allows you to fetch changing data over time
      const update = {...state};
      state.producers.forEach(producer => {
        // safely initialize
        update[producer.Country] = update[producer.Country] || [];
        if (!update[producer.country].find(producer) {
          // push onto
          update[producer.Country].push(producer);
        }
      });
      return update;
    })
  }
}

这保证在类中以安全的方式在状态更新上运行,并使您的关注点(获取)和派生(派生结构)分开且易于维护。


推荐阅读