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

react-insta-stories组件第一组故事结束后加载下一组异常求助

解决react-insta-stories自动切换下一组故事的问题

你遇到的核心问题是没跟踪当前展示的用户分组索引,仅直接更新items状态可能无法让组件正确触发下一组故事的渲染。以下是可行的实现方案:

实现思路

  1. 维护两个状态:currentPersonIndex记录当前正在展示的用户索引,items存储当前要展示的故事列表
  2. 初始化时加载第一个用户的故事
  3. 在onAllStoriesEnd回调中,判断是否还有下一个用户,若有则切换到下一个用户的故事;若已到最后一组,可选择循环回到第一组

完整代码示例

import { useState } from 'react';
import Stories from 'react-insta-stories';

// 你的people数据结构
const people = [
  {
    "name": "Sumesh",
    "stories": [
      { "url": "图片地址", "type": "image" },
      { "url": "视频地址", "type": "video" }
    ]
  },
  // 其他用户数据...
];

function StoryViewer() {
  // 初始化当前用户索引为0,加载第一个用户的故事
  const [currentPersonIndex, setCurrentPersonIndex] = useState(0);
  const [items, setItems] = useState(people[0]?.stories || []);

  const handleAllStoriesEnd = () => {
    // 计算下一个用户索引,用取模实现循环播放
    const nextIndex = (currentPersonIndex + 1) % people.length;
    setCurrentPersonIndex(nextIndex);
    // 更新当前展示的故事列表
    setItems(people[nextIndex].stories);
  };

  // 处理people为空的边界情况
  if (!people.length) {
    return <div>暂无故事内容</div>;
  }

  return (
    <Stories 
      stories={items} 
      onAllStoriesEnd={handleAllStoriesEnd} 
    />
  );
}

export default StoryViewer;

关键说明

  • 若不需要循环播放,可把nextIndex的计算改为currentPersonIndex < people.length - 1 ? currentPersonIndex + 1 : 0,或者到达最后一组后停止播放
  • 增加people[0]?.stories的可选链判断,避免初始时people为空导致的报错
  • 通过明确更新currentPersonIndex和items,确保组件能正确感知故事列表的变化并重新渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:36:05