首页 > 解决方案 > 从地图中设置变量

问题描述

我有以下代码:

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 扔在那里。

标签: javascriptreactjs

解决方案


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] }));
}),

推荐阅读