使用switch语句进行反应渲染

时间:2018-04-11 20:42:39

标签: javascript reactjs

我目前这样做是为了有条件地渲染某些组件:

render() {
    return (
        <React.Fragment>
            <div id="call_notes_app" className="row">
                <NavTree onNavChange={this.changeActiveGroup} />
                {this.state.shownGroup == 1 && <DiscoveryGroup/>}
                {this.state.shownGroup == 2 && <FinancialGroup/>}
                {this.state.shownGroup == 3 && <SalesStuffGroup/>}
            </div>
        </React.Fragment>
    );
}

当我尝试使用switch语句时,它不起作用(我在控制台中得到ERROR ABORT):

render() {
    return (
        <React.Fragment>
            <div id="call_notes_app" className="row">
                <NavTree onNavChange={this.changeActiveGroup} />

                {
                    switch(this.state.shownGroup) {
                        case 1:
                            <DiscoveryGroup/>
                            break;
                        case 2:
                            <FinancialGroup />
                            break;
                        default:
                            <SalesStuffGroup />
                    }
                }
            </div>
        </React.Fragment>
    );
}

有没有办法使用switch

执行此操作

2 个答案:

答案 0 :(得分:4)

switch用于单个陈述。更简洁的方法是在返回语句之前render() { let component = null; switch(this.state.shownGroup) { case 1: component = <DiscoveryGroup />; break; case 2: component = <FinancialGroup />; break; default: component = <SalesStuffGroup />; } return ( <React.Fragment> <div id="call_notes_app" className="row"> <NavTree onNavChange={this.changeActiveGroup} /> {component} </div> </React.Fragment> ); }

renderGroup(group) {
    switch (group) {
      case 1:
        return <DiscoveryGroup />;
      case 2:
        return <FinancialGroup />;
      default:
        return <SalesStuffGroup />;
    }
}

render() {
    return (
        <React.Fragment>
            <div id="call_notes_app" className="row">
                <NavTree onNavChange={this.changeActiveGroup} />
                {this.renderGroup(this.state.shownGroup)}
            </div>
        </React.Fragment>
    );
}

如果你最终拥有许多动态组件,那么将事情拆分为单独的方法会更加清晰:

{{1}}

答案 1 :(得分:-1)

React需要{}块中的表达式,因此需要将switch语句包装到IIFE中:

 {(() => {
   switch(this.state.shownGroup) {
     case 1:
         return <DiscoveryGroup/>
         break;
     case 2:
         return <FinancialGroup />
         break;
     default:
         return <SalesStuffGroup />
   }
 })()}

但我本人实际上更喜欢Immeadiately Accessed Array Literal(IAAL):

 {[,<DiscoveryGroup/>, <FinancialGroup />][this.state.showGroup] || <SalesStuffGroup />}