【问题标题】:How to generate permanent React keys for same string value in array?如何为数组中的相同字符串值生成永久 React 键?
【发布时间】:2020-03-30 16:35:31
【问题描述】:

我有一个用户输入文本的文本框。然后执行对特定关键字的搜索,并在这些关键字处拆分字符串。

第一个输入可能看起来像 E.g.

[
    0: "this is "
    1: "word"
    2: " a form field value with another "
    3: "word"
]

然后可能会进行更改以删除第一个重复的单词:

[
    0: "this is "
    1: " a form field value with another "
    2: "word"
]

如何为每个数组项创建一个持久键?我需要第二个 word 值具有与第一次生成时相同的 React 键,而不管数组位置如何。它是一个单独的组件实例,无论值是否相同。我现在有一个问题,删除其中一个拆分词将同时删除,因为删除第一个词后键会发生变化。

最佳做法是不使用数组索引,但我不确定在这种情况下如何生成唯一键。

【问题讨论】:

  • 在您的情况下,您似乎可以仅使用索引或将索引与诸如${index}${value} 之类的单词内容结合使用
  • 使用值作为键。
  • 感谢@xdeepakv,但密钥必须是唯一的。相同的词有相同的键。
  • 请检查我的答案!

标签: javascript arrays reactjs


【解决方案1】:

这是一个粗略的解决方案,但您可以将其视为字典程序。

class SomeComponent {
  constructor() {
    this.state = {
      words: ["this is ", "word", " a form field value with another ", "word"]
    };
    this.wordMap = this.state.words.reduce((m, x, index) => {
      m[index] = x;
      return m;
    }, {});
  }
  cleanWord() {
    let unique = new Set();
    for (let key in this.wordMap) {
      if (unique.has(this.wordMap[key])) {
        this.wordMap[key] = null; //duplicate
      } else {
        unique.add(this.wordMap[key]);
      }
    }
  }
  onDelete(index) {
    this.wordMap[index] = null;
  }
}
const dict = new SomeComponent();
dict.cleanWord();
console.log(dict.wordMap);

dict.onDelete(1);
console.log(dict.wordMap);
.as-console-row {color: blue!important}

【讨论】:

  • 我最终采用了这样的解决方案。
【解决方案2】:

你可以使用值作为键,并保持索引作为值

[
    "this is ": [0]
    "word": [1,3]
    " a form field value with another ":[2]
]

然后当你删除一个索引时,它会看起来像

[
    "this is ": [0]
    "word": [3]
    " a form field value with another ":[2]
]

您可以使用 reduce 从拆分的字符串中生成这种格式

let str = ["this is ", "word", " a form field value with another ", "word"]

let mapperObj = str.reduce((op, inp, index) => {
  op[inp] = op[inp] || []
  op[inp].push(index)
  return op
}, {})

console.log(mapperObj)

【讨论】:

  • @RobFyffe 这些是,你不能在对象中有重复的属性名称
【解决方案3】:

据我所知,您可以使用任何东西作为键,但您希望它们对于每个项目都是唯一的。

我建议使用 btoa(JSON.stringify(object)) 对您的项目进行 base64 处理,或者通过将索引附加到值 ${index}${value} 来创建如上所述的唯一键

【讨论】:

  • 在 React 中,键必须是唯一的。相同的词将具有相同的键。然后从数组中删除 a 值会更改索引,因此这意味着键不会是持久的。
【解决方案4】:

如果您可以将已删除的值标记为null,则可以使用索引作为键。无需额外过滤即可呈现此值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多