首页 > 解决方案 > 有没有办法保存组件实例

问题描述

我正在尝试制作一个页面,其中包含在组件之间导航的选项卡。但必须保存组件实例。因为当我返回一个页面时,我不想重新渲染组件。

   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

这是一种反模式,还是没有意义的东西?

标签: reactjs

解决方案


这可以使用 a 来完成single page atom,例如使用redux. 如果您将数据保留在组件inner state中,那么当组件渲染关闭时,它就会消失......


推荐阅读