为什么我的组件在状态更改时没有重新渲染?



存储在道具中的值1、2和3的值是Math.floor(Math.random()*100),所以当我设置State和numQuestions的值时,我想知道的是,numCorrect的变化和渲染方法正在被调用,因为我知道为什么这个渲染没有使三个值1,2,3再次再现,并且它们的值随着每次单击两个按钮而变化。

class App extends Component {
constructor(props) {
super(props)
this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
this.state = {
numQuestions : 0,
numCorrect : 0,
}
}
rightanswer= ()=> {
if(this.proposedAnswer === this.props.value1 + this.props.value2 + this.props.value3){
this.setState((oldstate)=> ({
numCorrect : oldstate.numCorrect +=1 ,
numQuestions : oldstate.numQuestions += 1 ,
}))
}else{
this.setState((oldstate)=> ({
numQuestions : oldstate.numQuestions += 1 ,
}))
}
}
falseanswer= ()=> {
if(this.proposedAnswer !== this.props.value1 + this.props.value2 + this.props.value3){
this.setState((oldstate)=> ({
numCorrect : oldstate.numCorrect +=1 ,
numQuestions : oldstate.numQuestions += 1 ,
}))
}else{
this.setState((oldstate)=> ({
numQuestions : oldstate.numQuestions += 1 ,
}))
}
}
render() {
return (
<div className="App">
<div className="game">
<h2>Mental Math</h2>
<div className="equation">
<p className="text">{`${this.props.value1} + ${this.props.value2} + 
${this.props.value3} = ${this.proposedAnswer}`}</p>
</div>
<button  onClick={() => this.rightanswer()}>True</button>
<button onClick={() => this.falseanswer()}>False</button>
<p className="text">
Your Score: {this.state.numCorrect}/{this.state.numQuestions}
</p>
</div>
</div>
);
}
}
export default App;

当状态发生变化时,组件将重新呈现。但是,您的道具不会更改,因为您没有从父组件传入新道具,所以value1value2value3保持不变。

如果您希望value在状态更改时发生更改,一种方法是将所有value移动到状态,在组件安装时初始化它们,并在组件更新时更新它们:

constructor(props) {
super(props);
this.state = {
numQuestions: 0,
numCorrect: 0
};
}
componentDidMount() {
this.generateValues();
}
componentDidUpdate(prevProps, prevState) {
if (this.state.numQuestions !== prevState.numQuestions) {
this.generateValues();
}
}
generateValues = () => {
const values = [...Array(3)].map(() => Math.floor(Math.random() * 100));
const correctAnswer = values.reduce((a, b) => a + b, 0);
const proposedAnswer = Math.floor(Math.random() * 3) + correctAnswer;
this.setState({
value1: values[0],
value2: values[1],
value3: values[2],
correctAnswer: correctAnswer,
proposedAnswer: proposedAnswer
});
};

Arrow函数没有this绑定(此处提供更多信息)。您还在buttonthis.falseansweronClick上调用它们。因此类找不到绑定,因此函数什么也不返回,因为它看起来不存在。此外,当我们将函数传递给事件处理程序,并且函数没有参数时,最佳实践是只传递这样的函数:onClick={myFunciton}

因此,在您的情况下,我会将这些箭头函数转换为方法,在constructor处绑定它们,并在onClick事件上调用它们

constructor(props) {
super(props)
this.proposedAnswer = Math.floor(Math.random() * 3) + this.props.value1 + this.props.value2 + this.props.value3;
this.state = {
numQuestions : 0,
numCorrect : 0,
}
this.falseAnswer = this.falseAnswer.bind(this);
}
falseAnswer () { ...}
render () {
return (
<button onClick={this.falseAnswer}>False</button>
);
}

相关内容

  • 没有找到相关文章

最新更新