reactjs - 有没有办法保存组件实例
问题描述
我正在尝试制作一个页面,其中包含在组件之间导航的选项卡。但必须保存组件实例。因为当我返回一个页面时,我不想重新渲染组件。
import React, { Component } from 'react'
class TabContent extends Component {
constructor(props) {
super(props)
const Component = this.props.currentTab.id
const activeTab = <Component />
this.state = {
openTabs: [activeTab],
activeTab: 0
}
}
componentWillReceiveProps(nextProps) {
const index = nextProps.tabs.indexOf(nextProps.currentTab)
if (nextProps.tabs.length > this.state.openTabs.length) {
const Component = nextProps.currentTab.id
const activeTab = <Component />
this.setState({
openTabs: this.state.openTabs.concat(activeTab),
activeTab: index
})
} else {
this.setState({
activeTab: index
})
}
}
render() {
const { activeTab, openTabs } = this.state
const Component = openTabs[activeTab]
return (
openTabs[activeTab]
)
}
}
export default TabContent
这是一种反模式,还是没有意义的东西?
解决方案
这可以使用 a 来完成single page atom
,例如使用redux
. 如果您将数据保留在组件inner state
中,那么当组件渲染关闭时,它就会消失......
推荐阅读
- android - 如何在主片段区域之外过渡 UI 元素?
- java - bindingResult.hasErrors() 总是返回 false
- python - 如何检查发送的表情是否是 Discord 默认表情并禁止其他表情?
- ios - ios横向模式下flutter camerapreview旋转90度
- python - 尝试处理弹出 Selenium Python 时出现 NoAlertPresentException 错误
- html - 单击导航窗格到子页面时,相对路径会中断
- c++ - 更新 R 版本后模块中的 Rcpp 分段错误
- postgresql - 如何使用 pgloader 将特定的整个模式从一个 Postgres 数据库迁移到另一个?
- c++ - c ++列表在设置差异后不调整大小
- ansible - Ansible 复制文件并从两个列表中获取文件的源和目标名称