Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/407.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript开关语句是否已损坏?_Javascript_Reactjs_Switch Statement - Fatal编程技术网

Javascript开关语句是否已损坏?

Javascript开关语句是否已损坏?,javascript,reactjs,switch-statement,Javascript,Reactjs,Switch Statement,我现在很困惑。我在React中有一个简单的switch语句,它行为不端,我不知道为什么 看看这个: alterHandler(keyName, value, profileType){ const newState = Object.assign({}, this.state); console.log('inside alterHandler in Profile') console.log('value of profileType: ', profileType)

我现在很困惑。我在React中有一个简单的switch语句,它行为不端,我不知道为什么

看看这个:

alterHandler(keyName, value, profileType){
    const newState = Object.assign({}, this.state);
    console.log('inside alterHandler in Profile')
    console.log('value of profileType: ', profileType)
    console.log('profileType equals local: ', profileType=='local')
    console.log('profileType equals db: ', profileType=='db')
    switch (profileType){
      case 'local':
        console.log('23235235235123523t2346 case local')
        newState['local'][keyName] = value;
      case 'db':
        console.log('23235235235123523t2346 case db')
        newState['db'][keyName] = value;
      case 'n/a':
        newState[keyName] = value;
      default:
        if(keyName=='animalType'){
          newState['showForward'] = true;
        }
        this.setState(newState, ()=>{
          console.log('after setting state in alterHandler 
          in Profile and value: ', this.state)
        });
    }
  }
如果我打电话给你

onChange={(e)=>{this.props.alterHandler('personalName', e.target.value, 'local')}} 
在输入语句中

我得到以下输出:

 value of profileType:  local index.js:216
 profileType equals local:  true index.js:217
 profileType equals db:     false index.js:218
 case local index.js:221
 case db  index.js:224
因此,即使
profileType
是“本地”的,case“db”也会触发

这里的体育世界正在发生什么?

请看一看。具体而言,本节:

与每个case标签关联的可选
break
语句可确保程序在执行匹配语句后脱离开关,并在开关后的语句处继续执行。如果省略了
break
,程序将在switch语句中的下一条语句继续执行


因此,如果您不添加break
子句,程序将不会退出
switch
作用域,并且将运行
default`操作,因为它不知道某个子句已经匹配。

当您创建一个
案例
时,开关将遍历案例,直到找到一个正确的案例。一旦发现这种情况,它将从那里开始执行代码。问题是,除非您从switch语句中
break
,否则它将继续进入其他情况

在switch语句中

    switch (profileType){
      case 'local':

它在本地执行所有操作,然后继续执行db,因为您没有
break

别忘了用
break结束每个案例
,否则您将陷入下一个案例。可能需要一些
中断
s。阅读一些文档:谢谢-我太习惯
中断
被用来提前停止执行,而不是结束子句语句。非常感谢。