javascript - 在类中使用 If-else。

标签 javascript reactjs

我们可以在 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/

相关文章:

javascript - react 错误 : is declared but its value is never read. [6133]

javascript - 这是否可以在使用 python 执行 javascript 后加载页面?

javascript - 如何使用 jquery json 获取多个下拉菜单

Javascript OOP 继承

javascript - 在react.js中使用select和option时弹出窗口不会打开

reactjs - 测试 create-react-app index.js 文件

javascript - 每 x 分钟运行一个 php 脚本(无 cron)

javascript - 如何预填充下拉列表

Javascript ESLint 错误 - 在条件表达式中不必要地使用 bool 文字

javascript - 如何将 reactjs 与 Google DFP/AdSense 一起使用