【问题标题】:Switching between controlled mode (by using `selectedIndex`) and uncontrolled mode is not supported in `Tabs``Tabs` 不支持在受控模式(通过使用`selectedIndex`)和不受控模式之间切换
【发布时间】:2019-05-28 20:36:30
【问题描述】:

我正在尝试在我的 next/react 应用程序中使用 react-tabs 实现一些选项卡。

我有主页project/:id,始终在0索引选项卡中打开,并且在选择每个选项卡时,选项卡名称会添加到路由中,例如:project/:id/one-tab

这样,如果我分享链接 project/:id/two-tab,该网站将在 1 索引选项卡中打开。

但我得到了错误

react-dom.development.js:20312 Uncaught Error: Switching between controlled mode (by usingselectedIndex) and uncontrolled mode is not supported inTabs. at Function.copyPropsToState (Tabs.js:65) at getDerivedStateFromProps (Tabs.js:50)

我的组件看起来像这样

   class Project extends React.Component {

       constructor(props) {

          super(props);
          resetIdCounter();

       }

   state = {
     tabIndex: null
   };

   static async getInitialProps({ query }) {
      return { query };
   }

 render() {
    const { query } = this.props;
    const { tabIndex } = this.state;

    const TAB = {
      tab1: 0,
      tab2: 1,
    };

     return (

            <div>
              <Tabs
                selectedIndex={tabIndex || TAB[query.tab]}
                onSelect={index => this.setState({ tabIndex: index })}
              >
                <StyledTabList>
                  <StyledTab
                    onClick={() =>
                      Router.replaceRoute("one-tab", { id })
                    }
                  >
                    One tab
                  </StyledTab>
                  <StyledTab
                    onClick={() => Router.replaceRoute("two-tab", { id })}
                  >
                    Two tab
                  </StyledTab>    
                </StyledTabList>
              </Tabs>
            </div>
      );

   }
 }

 export default Project;

【问题讨论】:

    标签: reactjs next react-tabs


    【解决方案1】:

    我在使用这个库时遇到了同样的错误。我能够通过确保在 return 函数之前定义传递给 selectedIndex 属性的值(不是 undefinednull)来解决它。

    所以改变这个:

    const TAB = {
          tab1: 0,
          tab2: 1,
        };
    
    return (
                <div>
                  <Tabs
                    selectedIndex={tabIndex || TAB[query.tab]}
                    onSelect={index => this.setState({ tabIndex: index })}
                  >
    
    

    进入这个:

    const TAB = {
          tab1: 0,
          tab2: 1,
        };
    const selectedIdx = tabIndex ? tabIndex : TAB[query.tab]
    return (
                <div>
                  <Tabs
                    selectedIndex={selectedIdx}
                    onSelect={index => this.setState({ tabIndex: index })}
                  >
    
    

    编辑: 您也可以在构造函数中设置 state.tabIndex = 0,因为您的 0 索引选项卡是您的默认选项卡。

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 2020-07-08
      • 2014-06-24
      • 2017-12-30
      • 2010-09-20
      • 2016-11-25
      • 2017-09-27
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多