React - 重构eval函数并提高代码质量

时间:2017-10-24 12:00:50

标签: javascript reactjs

我刚刚开始玩React,并构建了一个简单的计算器应用程序。 请有人能够就我可以采取的改进代码的步骤提出建议。

理想情况下,我想知道如何正确使用状态,以及如何重构我对eval函数的使用。

非常感谢您对如何做到这一点的任何反馈,以及:)

import React from 'react';

class Calculator extends React.Component {
  constructor(props){
      super(props);
      this.state = {
        prev: [],
        total: []
      };
  }

  inputDigit(int) {

    var newArr = this.state.total.slice();
    newArr.push(int);
    this.setState({total: newArr});

  }

  addition(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "+");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  minus(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "-");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  divide(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "/");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  multiply(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "*");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;
  }

  clearInput() {

    this.setState({total:[],prev:[]});

  }

  sum(currNum) {

    var store = this.arrToNum(currNum);
    var newArr = this.state.prev.slice();
    newArr.push(store);
    console.log(newArr.join(" "));
    var sum = eval(newArr.join(" "));

    this.setState({total:[sum]});

  }

  arrToNum(arr) {

    var test = Number(arr.join(''));

    return test;

  }

  makePretty(num) {

    var newNum = this.arrToNum(num);
    var formatNum = newNum.toLocaleString();

    return formatNum;

  }

  render() {
    return(
      <div className="Calculator">
        <div className="Screen">
          <p>{this.makePretty(this.state.total)}</p>
        </div>
        <div className="KeyPad">
          <div className="row">
            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>
          </div>
          <div className="row">
            <button className="square" onClick={() => this.inputDigit(4)}>4</button>
            <button className="square" onClick={() => this.inputDigit(5)}>5</button>
            <button className="square" onClick={() => this.inputDigit(6)}>6</button>
            <button className="square" onClick={() => this.minus(this.state.total)}>-</button>
          </div>
          <div className="row">
            <button className="square" onClick={() => this.inputDigit(1)}>1</button>
            <button className="square" onClick={() => this.inputDigit(2)}>2</button>
            <button className="square" onClick={() => this.inputDigit(3)}>3</button>
            <button className="square" onClick={() => this.multiply(this.state.total)}>*</button>
          </div>
          <div className="row">
            <button className="square" onClick={() => this.inputDigit(0)}>0</button>
            <button className="square" onClick={() => this.inputDigit(".")}>.</button>
            <button className="square" onClick={() => this.sum(this.state.total)}>=</button>
            <button className="square" onClick={() => this.divide(this.state.total)}>/</button>
          </div>
          <div className="row">
            <button className="square full" onClick={() => this.clearInput()}>CLEAR</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Calculator;

2 个答案:

答案 0 :(得分:2)

1 -

inputDigit(int) {
  this.setState({total: [
    ...this.state.total,
    int
  ]})
}

2 -

addition(prevNum) {
 let store = this.arrToNum(prevNum);
 let string = [...this.state.prev, store, '+'].join(' ');
 this.setState({total:[] , prev: [string]});
 return prevNum;
}

你必须遵循相同的模式来完成其余的功能

3-添加此功能

renderItem(value, onClick) {
   return <button className="square" onClick={onclick}>{value}</button> 
}

4-替换它:

<div className="row">
            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>
          </div>

用这个

<div className="row">
  {[
     ['7',() => this.inputDigit(7)],
     ['8',() => this.inputDigit(8)],
     ['9',() => this.inputDigit(9)],
     ['+',() => this.addition(this.state.total)],
   ].map(([value, onClick]) => this.renderItem(value, onClick)})

5-跟随所有视图的相同模式

答案 1 :(得分:0)

那是另一个代码审核......

import React from 'react'

class Calculator extends React.Component {
  state = {
    prev: [],
    total: []
  }

  inputDigit(int) {
    let {state} = this.state
    this.setState({
      total: [...total, int]
    })
  }

  action(prevNum, symbol) {
    let store = Number(prevNum.join(''))
    let {prev} = this.state
    let string = [...prev, store, symbol].join(' ')
    this.setState({total: [], prev: [str]})
    return prevNum
  }

  clearInput() {
    this.setState({total: [], prev: []})
  }

  sum(currNum) {
    let store = Number(currNum.join(''))
    let {prev} = this.state
    let sum = eval([...prev, store].join(' '))
    this.setState({total: [sum]})
  }

  makePretty(num) {
    return Number(num.join('')).toLocaleString()
  }
  renderItem(value, onClick) {
    if (!onClick) onClick = () => this.inputDigit(value)
    return (
      <button className="square" onClick={onclick}>
        {value}
      </button>
    )
  }
  render() {
    return (
      <div className="Calculator">
        <div className="Screen">
          <p>{this.makePretty(this.state.total)}</p>
        </div>
        <div className="KeyPad">
          <div className="row">
            {[
              [7],
              [8],
              [9],
              ['+', () => this.action(this.state.total, '+')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [4],
              [5],
              [6],
              ['-', () => this.action(this.state.total, '-')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [1],
              [2],
              [3],
              ['*', () => this.action(this.state.total, '*')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [0],
              ['.'],
              ['='],
              ['/', () => this.action(this.state.total, '/')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            <button className="square full" onClick={() => this.clearInput()}>
              CLEAR
            </button>
          </div>
        </div>
      </div>
    )
  }
}