2016-09-23 14 views
0

これはちょっと変わった言い方です。説明するのに役立つコードをいくつかレイアウトしましょう。私は単純な反応成分を書いています。この反応コンポーネントは、フォームを提出するフォームを持っています。これは今まで私が持っているものです:関数の戻り値を別の関数の戻り値とするにはどうすればいいですか

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 
    } 
} 

上記のコメントのように、私はフォーム提出の実行を停止したいだけです。私は、このタイプの状況でベストプラクティスを探しています。私は機能を抽象化したいが、その抽象化された機能の戻り値を条件として返り値として使用したい。ここ

+2

ifブランチでは 'true'を返し、elseブランチでは何も返さないようですが、あなたのコードはうまくいくようです。 – Bergi

+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 
} 

をITEまたは多分あなたはonSubmitメソッド内alertを置きたい、そしてcheckQuantityがさらに簡単になります。また、checkQuantityの名前をisInvalidQuantityのようにわかりやすい名前に変更することもできます。

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 

    } 
} 
0

問題は、あなただけのcheckQauntity()、あなたは戻り値に基づいて行動し、次に何をすべきかを決定したいの値を返すようにしたくないです。この場合、あなたが持っているコードはそれを行う方法と同じくらい良いものです。

しかし、より一般的なケースのために(あなたはちょうどあなたが以下のような何かを行うことができ、trueまたはfalseを返すされていません。

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

checkQuantity(){ 
var someNumber = ...someNumber; 
return someNumber; 
} 
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) 
    } 
} 

、戻り値はあなたの例ではない意味を持っている。私はWRと思い

関連する問題