Calc App React未定义

时间:2017-08-21 05:51:53

标签: reactjs

我在React中创建了一个计算器,我的状态值为displayValue,当我执行其中一个operationsMethod时,它会一直返回undefined。如果有人能提供帮助,我不确定我做错了什么,谢谢。

我认为必须使用我的performOperation方法做一些事情,但我不确定究竟是什么。

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {displayValue: '0' , waitingForOperand: false, operator: null, value: null}
    this.inputDigit = this.inputDigit.bind(this);
    this.inputDot = this.inputDot.bind(this);
    this.clear = this.clear.bind(this);
    this.toggleSign = this.toggleSign.bind(this);
    this.performOperation =  this.performOperation.bind(this);
  }

  clear() {
    const {displayValue} =  this.state;
    this.setState({
      displayValue: '0'
    });
  }

  inputDigit(digit) {
    const {displayValue, waitingForOperand} = this.state;
    if(waitingForOperand) {
      this.setState({
        displayValue: String(digit),
        waitingForOperand: false
      });
    } else {
    this.setState({
      displayValue: displayValue === '0' ? String(digit) : displayValue + digit
    });
  }
  }

  inputDot() {
    const {displayValue, waitingForOperand} =  this.state;
    if(waitingForOperand) {
      this.setState({
        displayValue: '.',
        waitingForOperand: false
      });
    }
    else if(displayValue.indexOf('.') === -1) {
      this.setState({
        displayValue: displayValue + '.'
      });
    }
  }

  toggleSign() {
    const {displayValue} = this.state;

    this.setState({
      displayValue : displayValue.charAt(0) === '-' ? displayValue.substring(1) : '-' + displayValue 
    })
  }

  percent() {
    const {displayValue} = this.state;
    const value = parseFloat(displayValue);

    this.setState({
      displayValue: String(value / 100)
    });
  }

  performOperation(nextOperator) {
    const {displayValue, operator, value} = this.state;
    const nextValue = parseFloat(displayValue);

    const operations = {
      '/' : (prevVal, nextValue) => prevVal / nextValue,
      '*' : (prevVal, nextValue) => prevVal * nextValue,
      '+' : (prevVal, nextValue) => prevVal + nextValue,
      '-' : (prevVal, nextValue) => prevVal - nextValue,
      '=' : (prevVal, nextValue) => nextValue
    }

    if(value == null) {
      this.setState({
        value: nextValue
      });

    } else if(operator) {
      const currentValue = value || 0;
      const computedValue = operations[operator](currentValue, computedValue);

      this.setState({
        value: computedValue,
        displayValue: String(computedValue)
      }) 
    }

    this.setState({
        waitingForOperand: true,
      operator: nextOperator
    })
  }

1 个答案:

答案 0 :(得分:1)

performOperations中的这一行存在问题

const computedValue = operations[operator](currentValue, computedValue);

应该是:

const computedValue = operations[operator](nextValue, currentValue);

无论如何,变量名有点误导。