You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在嵌套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>
  );
})}

说明

  1. 提前把目标字符串分割成单词数组words,方便后续计算前置单词的总长度
  2. 用reduce累加当前单词之前所有单词的长度,得到prevLettersCount
  3. 每个字母的全局索引就是prevLettersCount + letterIndex,同时把这个值作为Button的key,保证全局唯一(符合React对key的要求)
  4. 最终渲染的Text内容替换为这个全局索引,就能得到连续递增的输出

内容的提问来源于stack exchange,提问作者KursadJS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:01:05