使用 ES7 重构 React 组件状态

React component state refactoring using ES7

谁能帮我用 ES7 格式重构这段代码?我按照 ES7 语法设置了它,但我得到 "this.makeNewQuestion" undefined.

 import React, { Component } from 'react';

    class Game  extends Component{
     constructor(props) {
        super(props);
        const valuesArray = this.makeNewQuestion();
        this.state = {
          value1: valuesArray[0],
          value2: valuesArray[1],
          value3: valuesArray[2],
          proposedAnswer: valuesArray[3],
        };
      }

      makeNewQuestion = () => {
        const value1 = Math.floor(Math.random() * 100);
        const value2 = Math.floor(Math.random() * 100);
        const value3 = Math.floor(Math.random() * 100);
        const proposedAnswer = Math.floor(Math.random() * 3) + (value1 + value2 + value3);
        return [value1, value2, value3, proposedAnswer];
      };

      someOtherNonFatArrowMethod(){

      }

      render(){
      return <h2 />
     }
    }

我的ES7格式是这样的。它对我来说看起来是正确的,但我得到 this.makeNewQuestion 未定义。这对我来说没有任何意义。谁能帮我找出我在这里遗漏的东西?

class Game extends Component{
  state = {
    value1: this.generateQuestions()[0],
    value2: this.generateQuestions()[1],
    value3: this.generateQuestions()[2],
    proposedAnswer: this.generateQuestions()[3]
  };

  generateQuestions = () => {
    const value1 = Math.floor(Math.random() * 100);
    const value2 = Math.floor(Math.random() * 100);
    const value3 = Math.floor(Math.random() * 100);
    const proposedAnswer = Math.floor(Math.random() * 3) + (value1 + value2 + value3);
    return [value1, value2, value3, proposedAnswer];
  };

someNonFatArrowFunc(){}
render(){
 return <h2/>
}
}

另外,如何避免在状态中多次 运行 makeNewQuestion?我还能在哪里捕获 class?

中 makeNewFunction() 的结果

你可以将state赋值给IIFE并在里面做必要的逻辑。

const {
  Component
} = React

class Game extends Component {

  state = (() => {

    const random = (to, from = 0) => Math.floor(Math.random() * (to - from));

    const makeNewQuestion = () => {
      const value1 = random(100);
      const value2 = random(100);
      const value3 = random(100);
      const proposedAnswer = random(3) + (value1 + value2 + value3);
      return [value1, value2, value3, proposedAnswer];
    };

    const [value1, value2, value3, proposedAnswer] = makeNewQuestion();

    // if you want to use those functions later (ie. event handling ) you have to bind them .
    this.makeNewQuestion = makeNewQuestion;
    this.random = random;

    return {
      value1,
      value2,
      value3,
      proposedAnswer
    }

  })();

  someOtherNonFatArrowMethod() {

  }

  render() {
    return <h2 > Test < /h2>
  }
}

ReactDOM.render( < Game / > ,
  document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>