我有一个文本框,用户可以在其中输入文本。然后执行对特定关键字的搜索,并在这些关键字处拆分字符串。
第一个输入可能看起来像 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 键,无论数组位置如何。无论值相同,它都是一个单独的组件实例。我现在遇到一个问题,删除一个分割词将会同时删除两个分割词,因为删除第一个词后键会发生变化。
最佳实践建议不要使用数组索引,但我不确定在这种情况下如何生成唯一 key 。
最佳答案
这是一个粗略的解决方案,但您可以将其视为一个字典程序。
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}
关于javascript - 如何为数组中的相同字符串值生成永久的 React 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60935172/