如何在嵌套Map中实现全局递增的唯一Key?
实现React中全局递增的索引输出
原React JSX代码如下:
{'The Lord of the Rings'.split(' ').map((word, wordIndex) => ( <View key={wordIndex}> {word.split('').map((letter, letterIndex) => ( <Button key={letterIndex}> <Text> {letterIndex} </Text> </Button> ))} </View> ))}
这段代码的输出为:
012 0123 01 012 01234
想要实现全局递增的唯一索引,让输出变为:
012 3456 78 91011 121314151617
修改方案
核心思路是计算每个字母的全局累计索引——当前字母之前所有单词的总长度,加上当前字母在单词内的索引。
修改后的代码如下:
const text = 'The Lord of the Rings'; const words = text.split(' '); {words.map((word, wordIndex) => { // 计算当前单词之前所有单词的总字母数 const prevLettersCount = words.slice(0, wordIndex).reduce((total, w) => total + w.length, 0); return ( <View key={wordIndex}> {word.split('').map((letter, letterIndex) => { // 全局唯一索引 = 前面总字母数 + 当前字母在单词内的索引 const globalIndex = prevLettersCount + letterIndex; return ( <Button key={globalIndex}> <Text>{globalIndex}</Text> </Button> ); })} </View> ); })}
说明
- 提前把目标字符串分割成单词数组
words,方便后续计算前置单词的总长度 - 用
reduce累加当前单词之前所有单词的长度,得到prevLettersCount - 每个字母的全局索引就是
prevLettersCount + letterIndex,同时把这个值作为Button的key,保证全局唯一(符合React对key的要求) - 最终渲染的
Text内容替换为这个全局索引,就能得到连续递增的输出
内容的提问来源于stack exchange,提问作者KursadJS
相关产品推荐
相关产品推荐

