javascript - 从地图中设置变量
问题描述
我有以下代码:
let pa = 0;
let pw = 0;
let pc = 0;
let pi = 0;
let pr = 0;
this.state.array.data.map((i) => {
if (i.mdn === this.queryParams.mdn && i.sources != null) {
return (i.sources.map((sources) => {
if (sources.source.toString().toLowerCase() === "a") {
pa = sources.t.sessions.u
}
if (sources.source.toString().toLowerCase() === "w") {
pw = sources.t.sessions.u
}
if (sources.source.toString().toLowerCase() === "c") {
pc = sources.t.sessions.u
}
if (sources.source.toString().toLowerCase() === "i") {
pi = sources.t.sessions.u
}
if (sources.source.toString().toLowerCase() === "r") {
pr = sources.t.sessions.u
}
}))
}
},
this.setState({
web: [],
app: [],
preference: [{a: pa}, {w: pw}, {c: pc}, {i: pi}, {r: pr}]
}),
一旦我进入设置状态,它实际上并没有设置它,它只需要 0 并将 throws 扔在那里。
解决方案
Array.prototype.map
尝试Array.prototype.forEach
通过键设置首选项对象,而不是使用。
要保留键的顺序,请创建所需顺序的数组。
let order = [ 'a', 'w', 'c', 'i', 'r' ];
preference = {
a : 0,
w : 0,
c : 0,
i : 0,
r : 0
};
this.state.array.data.forEach((item) => {
if (item.mdn === this.queryParams.mdn && item.sources != null) {
return item.sources.forEach((entry) => {
var key = entry.source.toString().toLowerCase();
preference[key] = entry.t.sessions.u;
});
}
});
this.setState({
web: [],
app: [],
preference: order.map(key => ({ [key] : preference[key] }));
}),
推荐阅读
- flutter - 颤振抽屉溢出
- json - [Youtube api, json]删除我们 Youtube 播放列表中的一个视频后,内容不显示
- java - 如何videoview旋转y轴?视频
- php - 覆盖变量中的名称
- sql - 创建类型时如何设置常量值?
- javascript - 尽管在 WordPress 网站的页脚中排队,为什么我的自定义 JavaScript 没有持续触发?
- python - 编码高基数变量
- reactjs - 将 dispatch 作为 prop 传递给共享组件,从既是功能组件又是类组件的组件
- stripe-payments - 在测试中与来自其他域的网页交互
- java - 卡夫卡生产者禁用