我们可以在 Javascript 类中使用 if-else 语句
吗?
我在 react 状态类中工作。
在类里面我做了这样的事情
import React, { Component } from 'react';
import Aux from '../../HOC/Aux.js';
import Burger from '../../burger/burger.js'
import BuildControls from '../../burger/Build-Control/build-controls.js';
class BurgerBuilder extends Component {
state = {
ingredient: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 4,
purchaseable: false
}
//Something
if (this.state.totalPrice != 4) {
let newState = {
...this.state.ingredient
}
this.setState({ingredient: newState})
}
但随后它开始抛出此错误
Unexpected token (63:4)
61 |
62 |
> 63 | if (this.state.totalPrice != 4) {
| ^
64 | let newState = {
65 | ...this.state.ingredient
66 | }
如果我们可以使用 if-else 语句,那么知道为什么这不起作用吗?
最佳答案
您可以将该逻辑移至方法 setIngredientState
并从构造函数
调用它
代码:
import React, { Component } from 'react';
import Aux from '../../HOC/Aux.js';
import Burger from '../../burger/burger.js'
import BuildControls from '../../burger/Build-Control/build-controls.js';
class BurgerBuilder extends Component {
state = {
ingredient: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 4,
purchaseable: false
}
constructor() {
this.setIngredientState();
}
//Something
setIngredientState() {
if (this.state.totalPrice != 4) {
let newState = {
...this.state.ingredient
}
this.setState({
ingredient: newState
})
}
}
}
关于javascript - 在类中使用 If-else。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50675871/