React中状态的选择性合并

时间:2019-02-26 15:16:24

标签: javascript arrays json

我在React中设置了以下内容:

  initPlatforms() {
    this.setState({rules: [
      {what: "platform", matches: "ios"},
      {what: "platform", matches: "android"},
      {what: "platform", matches: "windows"},
      {what: "platform", matches: "linux"},
      {what: "platform", matches: "mac"},
    ]})
  }

问题是,我想与现有状态进行选择性合并。如果what/matches字段上有匹配项,则忽略它并添加其余部分。现有状态的示例可能是:

{"id":"cbd6defd-5f60-447f-8d31-f9ce75a7604a","matches":"android","url":"http://www.google.co.uk","what":"platform"}

如何轻松地添加丢失的状态而不覆盖原始状态?

3 个答案:

答案 0 :(得分:0)

我不太了解您想做什么。如果要向状态添加元素,只需使用javascript传播方法即可,

const addState = {
"id":"cbd6defd-5f60-447f-8d31-f9ce75a7604a",
"matches":"android",
"url":"http://www.google.co.uk",
"what":"platform"
}

this.setState({rules: [... this.state.rules, addState]})

使用...this.state.rules,您将添加所有现有状态,并将此新内容添加到其中。

干杯!

答案 1 :(得分:0)

const rules = [
  {what: "platform", matches: "ios"},
  {what: "platform", matches: "android"},
  {what: "platform", matches: "windows"},
  {what: "platform", matches: "linux"},
  {what: "platform", matches: "mac"},
];

const { what, platform } = this.state;

this.setState({
  rules: rules.filter((rule) => rule.what !== what || rule.platform !== platform)
});

答案 2 :(得分:0)

您可以遍历新闻规则并检查它们是否存在于现有状态。

Yes