javascript - 从组件外部调用 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)} 的身份访问但没有用,只是给了我空白空间。请各位大侠帮忙谢谢
解决方案
当您使用以下方法导入函数时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)
用上面的代码替换。
推荐阅读
- c# - 为什么我的后台工作人员在使用 Task.Delay 时会死锁?
- mysql - 将图像插入 SQL 表:插入语句中的语法错误
- ubuntu - 在 Ubuntu 上安装 GitLab:“无法解析主机:packages.gitlab.com”
- python - 为什么 Raspberry Pi 中带有 arduPi 库的 Arduino 代码不起作用?
- quectel - BG95 无法激活 - AT+QIACT=1 返回错误
- regex - Powershell中的多行正则表达式查找失败
- c++ - 如何在 C++ 中访问子类
- c++ - C ++在两个分离的线程之间共享非阻塞队列和互斥锁
- android - 在 ListView 中对片段进行排序
- javascript - 如何修改只读 ng-app 的结果?