如何将所有子功能重构为仅一个?

问题描述

我是React.js的初学者。尝试优化我的代码(reactjs上的一个简单计算器)。 我有很多子功能可以处理某些操作,例如添加新的Number或选择Operation(+,-)等。如何重构它们,使一个功能只能在一个地方处理所有操作?

来自App.js的代码

export default class App extends Component {
    state = {
        value: [],setValue: '',operation: ''
}

handleAddNumber = (nbr) => {
    // console.log( 'val: ' + nbr)
    const val = this.state.value
    if (val.length === 10){
        return console.log('Max size!')
    } else if (this.state.value === '0' ) {
        this.setState({
            value: nbr
        })
    } else {
        this.setState({
            value: this.state.value + nbr
        })
    }
    // console.log( 'State: ' + this.state.value)
}

handleOperation = (val) => {
    this.setState({
        setValue: this.state.value,value: [],operation: val
    })
}

handleEqual = () => {
    let sum;
    let operation = this.state.operation;
    let number1 = parseFloat(this.state.value);
    let number2 = parseFloat(this.state.setValue);

    if (operation === '+') {
        sum = number2 + number1;
    } else if (operation === '-') {
        sum = number2 - number1;
    } else if (operation === '*'){
        sum = number2 * number1;
    } else if (operation === '/') {
        sum = number2 / number1;
    } else if (operation === '%') {
        sum = number1 / 100;
    } else if (typeof sum === "undefined") {
        return
    }

    // const val = sum.toString();

    if (sum.toString().length >= 9) {
        this.setState({
            value: sum.toPrecision(8).toString()
        })
    } else {
        this.setState({
            value: sum.toString()
        })
    }
}

handlePercent = () => {
    let number1 = parseFloat(this.state.value);
    this.setState({
        value: number1 / 100
    })
}

handleSign = () => {
    let number = parseFloat(this.state.value);
    let sum = number * (-1);
    this.setState({
        value: sum
    })
}

addNbrDot = () => {
    const nbr = this.state.value
    const str = nbr.toString();
    const hasDot = str.includes('.',0);
    if (str.length === 0) {
        this.setState({
            value: 0 + '.'
        })
    } else if (hasDot) {
        console.log('double dots')
    } else {
        this.setState({
            value: this.state.value + '.'
        })
    }
}

handleAC = () => {
    this.setState({
        value: '0'
    })
}

render() {
    return (
    <div className="App">
        <div className="App-Box">
            <header className="App-header">
                <h1>Calculator</h1>
            </header>
            <main>
                <display value = { this.state.value }/>
                <Buttons handleAC = { this.handleAC }
                         handleSign = { this.handleSign }
                         handlePercent = { this.handlePercent }
                         handleEqual = { this.handleEqual }
                         handleOperation = { this.handleOperation }
                         addNumberDot={this.addNbrDot}
                         handleAddNumber = { this.handleAddNumber } />
            </main>
        </div>
    </div>
    );
}

您可以在github上找到所有源代码https://github.com/dauren2089/react-calculator.git

我愿意接受任何批评和建议。

解决方法

一种简单的方法是创建一个新函数,将所有其他函数包装在其中。新函数接受一个参数(可能是字符串),该参数定义了您希望执行的操作类型(例如“ add”,“ equal”等)。然后使用javascript switch/case statement触发要使用的函数并返回结果。

让我用您的代码举例说明。.

handleOperation = (operation,nbr) => {
  switch(operation) {
    case 'add':
      // console.log( 'val: ' + nbr)
      const val = this.state.value
      if (val.length === 10){
          return console.log('Max size!')
      } else if (this.state.value === '0' ) {
          this.setState({
              value: nbr
            })
      } else {
          this.setState({
              value: this.state.value + nbr
          })
      }
      // console.log( 'State: ' + this.state.value)
      return val;
    break;
    case "equal":
      // insert whatever you want here
    break;
    default:
      // whatever you want to do if no operations match
      console.log("handleOperation: Incorrect operation - ",operation);
  }
}

然后在调用函数时要牢记所要考虑的数字和操作。

handleOperation("add",32);