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

React中基于递增lineIndex切片不可变字符串状态实现换行续显

解决方法

核心思路是记录每一行结束时的单词位置,让新行精准截取后续内容,而非重复全量文本。具体实现步骤如下:

  1. 新增状态存储每一行的结束单词索引
    这个数组的每个元素对应某一行最后一个单词的下一个索引,方便后续行从该位置开始截取内容:
const [lineEndIndices, setLineEndIndices] = useState([0]);
  1. 监听行索引切换,记录上一行的结束位置
    当切换到新行时,把当前完整文本的单词数量记录下来,作为上一行的结束标记:
useEffect(() => {
  // 仅在切换到新行时记录结束位置
  if (currentLineIndex >= lineEndIndices.length) {
    const words = transcript.split(' ');
    setLineEndIndices(prev => [...prev, words.length]);
  }
}, [currentLineIndex, transcript]);
  1. 重新编写行内容更新逻辑
    每次文本更新时,根据当前行的起始位置(上一行的结束位置)截取对应内容:
useEffect(() => {
  const words = transcript.split(' ');
  const updatedLines = [...lines];
  
  // 计算当前行的起始单词索引
  const startIndex = currentLineIndex === 0 ? 0 : lineEndIndices[currentLineIndex - 1];
  // 截取从起始索引到末尾的单词并转为字符串
  updatedLines[currentLineIndex] = words.slice(startIndex).join(' ');
  
  setLines(updatedLines);
}, [transcript, currentLineIndex, lineEndIndices, lines]);
  1. 初始化行状态
    确保初始时至少有一行空内容:
const [lines, setLines] = useState(['']);

修改后就能实现你想要的效果:

  • burned house stone stone bird
  • stone shopping cart flying stone stone stone

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:22:16