有人能帮我把这段代码重构成ES7格式吗?我按照ES7语法设置了它,但是我没有定义"this.makeNewQuestion“。
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?我还能在哪里捕获类中makeNewFunction()的结果呢?
发布于 2020-06-03 23:42:29
您可以将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>
https://stackoverflow.com/questions/62176692
复制相似问题