在类中使用If-else。

时间:2018-06-04 07:58:34

标签: javascript reactjs

我们可以在Javascript类中使用if-else statement吗?

我在反应有状态的班级工作。

在课堂上我做了类似的事

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语句,那么任何想法都不能解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您可以将该逻辑移至方法setIngredientState并从constructor

调用它

代码:

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

答案 1 :(得分:1)

在使用组件时,您应该在函数内部使用if语句。

您可以在组件安装时或更新时执行此操作,如下所示:

*/ This will only occur once, at the moment the component is mounted */
componentDidMount() {
  if (this.state.totalPrice != 4) {
    let newState = {
      ...this.state.ingredient
    }
    this.setState({ingredient: newState})
  }
}

// This will happen every time a prop or state changes, which triggers a re-render of the component. This can trigger a recursive loop if you're not careful
componentDidUpdate() {
  if (this.state.totalPrice != 4) {
    let newState = {
      ...this.state.ingredient
    }
    this.setState({ingredient: newState})
  }
}

您还可以在组件呈现时设置if语句:

render() {
  if (this.state.totalPrice != 4) {
    let newState = {
      ...this.state.ingredient
    }
    this.setState({ingredient: newState})
  }
}

PS。另请注意,在比较Javascript中的值时,您不应该使用!=,因此它更好地使用!==,因为它还会比较类型而不仅仅是值。在你的情况下" 4"和4是一样的。