从组件外部调用switch语句

时间:2018-12-05 17:47:22

标签: javascript reactjs

我的天气应用程序有一个很大的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)}的身份访问,但没有工作,只是给了我空白。 伙计们,请帮助 谢谢

2 个答案:

答案 0 :(得分:1)

使用以下命令导入函数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)替换为上面的代码。

答案 1 :(得分:0)

console.log语句替换return

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: 
     return 'thunder_icon';
       break;

...
  }}