javascript - 将对象数组过滤到新数组中
问题描述
在反应我有:
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
每个国家设置状态之后我需要另一个声明,但我似乎无法让它发挥作用。
解决方案
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;
})
}
}
这保证在类中以安全的方式在状态更新上运行,并使您的关注点(获取)和派生(派生结构)分开且易于维护。
推荐阅读
- javascript - 如何为 Web 开发安装 NumJs?
- java - 使用 JAMOD 读取正确的 Schneider Momentum PLC 寄存器或线圈地址
- python - 将输出标签值保存到 csv
- python - 在两个 RaspberryPi 之间使用 Python xmlrpc 会导致连接被拒绝错误
- javascript - HTML & CSS: 带有基于 Scroll 的覆盖导航栏的嵌入式视频
- angular - 从 Angular 到 Spring 的多部分发布请求
- python - Python Twisted/Reactor 无法将消息发送到服务器/客户端
- python - 如何计算熊猫系列中列表的元素
- django - Letsencrypt 登台和生产服务器上的 SSL 证书
- regex - 正则表达式禁止撇号和连字符之前或之后的任何空格