fix(SubTabContainer): 修复 Tab 懒加载失效问题
- 添加 visitedTabs 状态记录已访问的 Tab 索引 - Tab 切换时更新已访问集合 - TabPanels 中实现条件渲染:只渲染当前或已访问过的 Tab 修复前:tabs.map() 会创建所有组件实例,导致 Hook 立即执行 修复后:仅首次访问 Tab 时才渲染组件,真正实现懒加载 效果:初始加载从 N 个请求减少到 1 个请求 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -118,6 +118,11 @@ const SubTabContainer: React.FC<SubTabContainerProps> = memo(({
|
|||||||
// 当前索引
|
// 当前索引
|
||||||
const currentIndex = controlledIndex ?? internalIndex;
|
const currentIndex = controlledIndex ?? internalIndex;
|
||||||
|
|
||||||
|
// 记录已访问的 Tab 索引(用于真正的懒加载)
|
||||||
|
const [visitedTabs, setVisitedTabs] = useState<Set<number>>(
|
||||||
|
() => new Set([controlledIndex ?? defaultIndex])
|
||||||
|
);
|
||||||
|
|
||||||
// 合并主题
|
// 合并主题
|
||||||
const theme: SubTabTheme = {
|
const theme: SubTabTheme = {
|
||||||
...THEME_PRESETS[themePreset],
|
...THEME_PRESETS[themePreset],
|
||||||
@@ -132,6 +137,12 @@ const SubTabContainer: React.FC<SubTabContainerProps> = memo(({
|
|||||||
const tabKey = tabs[newIndex]?.key || '';
|
const tabKey = tabs[newIndex]?.key || '';
|
||||||
onTabChange?.(newIndex, tabKey);
|
onTabChange?.(newIndex, tabKey);
|
||||||
|
|
||||||
|
// 记录已访问的 Tab(用于懒加载)
|
||||||
|
setVisitedTabs(prev => {
|
||||||
|
if (prev.has(newIndex)) return prev;
|
||||||
|
return new Set(prev).add(newIndex);
|
||||||
|
});
|
||||||
|
|
||||||
if (controlledIndex === undefined) {
|
if (controlledIndex === undefined) {
|
||||||
setInternalIndex(newIndex);
|
setInternalIndex(newIndex);
|
||||||
}
|
}
|
||||||
@@ -197,11 +208,16 @@ const SubTabContainer: React.FC<SubTabContainerProps> = memo(({
|
|||||||
</TabList>
|
</TabList>
|
||||||
|
|
||||||
<TabPanels p={contentPadding}>
|
<TabPanels p={contentPadding}>
|
||||||
{tabs.map((tab) => {
|
{tabs.map((tab, idx) => {
|
||||||
const Component = tab.component;
|
const Component = tab.component;
|
||||||
|
// 懒加载:只渲染已访问过的 Tab
|
||||||
|
const shouldRender = !isLazy || visitedTabs.has(idx);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TabPanel key={tab.key} p={0}>
|
<TabPanel key={tab.key} p={0}>
|
||||||
{Component ? <Component {...componentProps} /> : null}
|
{shouldRender && Component ? (
|
||||||
|
<Component {...componentProps} />
|
||||||
|
) : null}
|
||||||
</TabPanel>
|
</TabPanel>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
Reference in New Issue
Block a user