我如何使用函数的返回值作为另一个函数的返回值

时间:2016-09-23 01:50:48

标签: javascript reactjs

我可能会措辞这有点奇怪。让我列出一些代码来帮助解释。我正在编写一个简单的反应组件。这个反应组件有一个表格,我提交表格。这就是我到目前为止所做的:

onSubmit(event){
  event.preventDefault()
  if (this.checkQuantity()){
    // this is what i want to be simpler, the return value i want is already in the checkQuantity function in the if condition
    return true
  } else {
    let itemId = this.props.item.id
    let quantity = this.state.quantity
    this.props.onTransaction(itemId, quantity)
  }
}
checkQuantity(){
  if (this.state.quantity > this.props.item.quantity){
    alert("Can't buy what's not there!")
    return true
  } else {
    return false
  }
}

与上面的评论一样,我只想停止执行表单提交。我想,我只是在这种情况下寻找最佳实践。我希望抽象功能,但在条件中使用抽象功能的返回值作为返回。

4 个答案:

答案 0 :(得分:3)

我会写

onSubmit(event) {
  event.preventDefault()
  if (!this.checkQuantity()) {
    let itemId = this.props.item.id
    let quantity = this.state.quantity
    this.props.onTransaction(itemId, quantity)
  }
}
checkQuantity() {
  const isToomuch = this.state.quantity > this.props.item.quantity;
  if (isToomuch) {
    alert("Can't buy what's not there!")
  }
  return isToomuch
}

或者您可能希望将alert置于onSubmit方法中,然后checkQuantity变得更加简单。您还可以将checkQuantity重命名为更具描述性的内容,例如isInvalidQuantity

答案 1 :(得分:0)

onSubmit(event){
  event.preventDefault()
  return checkQuantity();
}
checkQuantity(){
  if (this.state.quantity > this.props.item.quantity){

alert("Can't buy what's not there!")
return true

  } else {

let itemId = this.props.item.id
let quantity = this.state.quantity
this.props.onTransaction(itemId, quantity)

return false

  }
}

答案 2 :(得分:0)

这里的问题是你不只是想返回checkQauntity()的值,你想对返回值进行操作然后决定做什么。在这种情况下,您拥有的代码与任何方式一样好。

但是对于更一般的情况(你不只是返回真或假,你可以做以下事情:

onSubmit(event){
 event.preventDefault();
 var check = checkQuantity();
 if (check > 6 ){
   return check;
 }
 else {
   //do something else..
 }
}

checkQuantity(){
 var someNumber = ...someNumber;
 return someNumber;
}

答案 3 :(得分:0)

我觉得你在不必要地拆分功能。以下代码不足够吗?

onSubmit(event){
   event.preventDefault()
   if (this.state.quantity > this.props.item.quantity){
     alert("Can't buy what's not there!")
   } else {
     let itemId = this.props.item.id
     let quantity = this.state.quantity
     this.props.onTransaction(itemId, quantity)
   }
}

此外,与其他人一样,返回值在您的示例中没有意义,因为您没有检查它。

相关问题