描述:
Tabs组件在来回切换的过程中,造成TabPane中包含的相同子组件重复渲染,例如:
<Tabs
activeKey={tabActiveKey}
onChange={(key: string) => this.changeTab(key)}
type="card"
>
<TabPane tab={"对外授权"} key="/authed-by-me">
<AuthedCollections
collectionType={this.collectionType}
/>
</TabPane>
<TabPane tab={"申请权限"} key="/authed-to-me">
<AuthedCollections
collectionType={this.collectionType}
/>
</TabPane>
</Tabs>
changeTab = (key: string) => {
this.collectionType = key === '/authed-by-me' ? CollectionEnums.AUTHED_TO_GRANT : CollectionEnums.AUTHED_TO_APPLY;
this.setState({
tabActiveKey: key
})
};
分析:
在Tabs的onChange监听函数changeTab中调用setState,造成页面重新render。antd 的策略是,只渲染当前的。当用户切换过后,不删除之前渲染过的节点。所以点击切换会逐渐增多。为的是防止用户在 mount 阶段调用异步请求导致切换时反复渲染。所以 render 数量随着上层刷新而整体刷新并增加是预期行为。
解决方案:
运用react的条件渲染,在每一次tab切换的时候将上个页面移出Dom树
<Tabs
activeKey={tabActiveKey}
onChange={(key: string) => this.changeTab(key)}
type="card"
>
<TabPane tab={"对外授权"} key="">
{
this.collectionType === CollectionEnums.AUTHED_TO_GRANT &&
<AuthedCollections
collectionType={this.collectionType}
/>
}
</TabPane>
<TabPane tab={"申请权限"} key="/authed-to-me">
{
this.collectionType === CollectionEnums.AUTHED_TO_APPLY &&
<AuthedCollections
collectionType={this.collectionType}
/>
}
</TabPane>
</Tabs>