js错误集锦 函数在一个map循环遍历中进行返回值返回 结果在调用该函数时收不到返回值

错误代码:

superviseFilter = () => {
	let company = this.props.cooperativeState.allCompany
	if(this.state.inspection.msName){
		let list = null
		company.map(item => {
			if(item.comName == this.state.inspection.msName){
				let a = item.comId
				if(this.state.inspection.superviseType == '137-01'){//港口
				   let wharfs = this.props.superviseState.allWharfs
				   wharfs = wharfs.filter(wharf => wharf.comId == a)
				   return wharfs.map(wharf => wharf.wharfName)
				}else if(this.state.inspection.superviseType == '137-02'){//航道
				   let waterways = this.props.superviseState.allWaterways
				   waterways= waterways.filter(waterway => waterway.orgId.includes(a))
				   return waterways.map(waterway => waterway.waterwayName)
				}
			}
		})
		alert('执行')
	}else{
	
	}
}

分析:在该函数的map循环遍历中进行返回,理应来说return之后他不会往下执行了,结果打印时你会发现,他继续执行了,所以说这样写是错误的

正确代码如下:

superviseFilter = () => {
	let company = this.props.cooperativeState.allCompany
	if(this.state.inspection.msName){
		let list = null
		company.map(item => {
			if(item.comName == this.state.inspection.msName){
				let a = item.comId
				if(this.state.inspection.superviseType == '137-01'){//港口
				   let wharfs = this.props.superviseState.allWharfs
				   wharfs = wharfs.filter(wharf => wharf.comId == a)
				   list = wharfs.map(wharf => wharf.wharfName)
				}else if(this.state.inspection.superviseType == '137-02'){//航道
				   let waterways = this.props.superviseState.allWaterways
				   waterways= waterways.filter(waterway => waterway.orgId.includes(a))
				   list = waterways.map(waterway => waterway.waterwayName)
				}
			}
		})
		return list
	}else{
	
	}
}

ok,我也是第一次遇到,纠结了好一会,终于解决了

你可能感兴趣的:(js错误集锦 函数在一个map循环遍历中进行返回值返回 结果在调用该函数时收不到返回值)