首页 > 解决方案 > 从组件外部调用 switch 语句

问题描述

我的天气应用程序有一种大的 switch 语句,我有很多 id 正在进行,我发现它使我的主文件如此之大,所以我想为我的所有 switch 语句创建一个文件并在我的组件中调用它但是我不能

这是开关代码

export   function switchCode (id){
switch(id){
    case 200:
    case 201:
    case 202:
    case 210:
    case 211:
    case 212:
    case 221:
    case 230:
    case 231:
    case 232: 
     console.log('thunder_icon');
       break;

     case 300:
     case 301:
     case 302:
     case 310:
     case 311:
     case 312:
     case 313:
     case 314:
     case 321:
     console.log('cloud rainy');
       break;

     case 500:
     case 501:
     case 502:
     case 503:
     case 504:
     case 511:
     case 520:
     case 521:
     case 522:
     case 531:
     console.log('rainy with sun');
         break;

     case 600:
     case 601:
     case 602:
     case 611:
     case 612:
     case 615:
     case 616:
     case 620:
     case 621:
     case 622:
     console.log('snow icon');
         break;

     case 701:
     case 711:
     case 721:
     case 731:
     case 741:
     case 751:
     case 761:
     case 762:
     case 771:
     case 781:
     console.log('hot icon or just sun or fog');
       break;

     case 800:
     console.log('big sunny');
      break;

     case 801:
     case 802:
     case 803:
     case 804:
     console.log('sun with cloud');
       break;

  }}

我试图以 {this.props.switchCode(500)} 的身份访问但没有用,只是给了我空白空间。请各位大侠帮忙谢谢

标签: javascriptreactjs

解决方案


当您使用以下方法导入函数时switchCode

import {switchCode} from './switch_weather_codes';

switchCode函数可用作局部变量。您只需要使用以下方式访问它:

switchCode(id);

请注意,这只会调用该console.log()函数。如果您确实需要其中的值,请将其更改console.log()return.

当你尝试使用this.props.switchCode(id)时,React 会尝试找到一个属性switchCode,它不是,而只是一个局部变量。this.props.switchCode(id)用上面的代码替换。


推荐阅读