forEach 使用 try{}catch{} 如何中断循环

2020-08-08  本文已影响0人  小李不小

foreach 使用 break 是无法中断循环的,看下面代码,是怎么来解决这种问题的

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
 
<div id="example"></div>
<script type="text/babel">


class Hello extends React.Component{

//第一个是组件初始化(initialization)阶段
constructor(props){
    //初始化状态
    super(props)

    //初始化状态
    this.state={
        list:['1','2'],
    }
}

}

//button 点击事件
hdClick=()=>{
    const {val,list}=this.state; //获取到val 和 list 
    //es5 写法  val=this.state.val;  list=this.state.list
        list.push(val); //把输入的内容 push到list里面

    try{

        list.forEach((item)=>{
             if(item=='1'){
                 console.log('item==1成功')
                // 条件成功,抛出错误
                throw new Error('条件成功,抛出错误')
             }
         })

    }catch(e){
        console.log('foreach-err',e.message)
    }

    

    this.setState({ //赋值
        list:list
    })

    console.log('listpush----',list)
}

    render(){
return <div>
<button onClick={this.hdClick}>点击新增数据</button>
</div>

        
    }

    






}


ReactDOM.render(
    <Hello></Hello>,
    document.getElementById('example')
    )


</script>
 
</body>
</html>
看下面的结果,完美解决了foreach 中断的问题
image.png
上一篇下一篇

猜你喜欢

热点阅读