foreach 使用 break 是無法中斷循環(huán)的惠况,看下面代碼喊废,是怎么來解決這種問題的
<!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){
//初始化狀態(tài)
super(props)
//初始化狀態(tài)
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); //把輸入的內(nèi)容 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}>點擊新增數(shù)據(jù)</button>
</div>
}
}
ReactDOM.render(
<Hello></Hello>,
document.getElementById('example')
)
</script>
</body>
</html>