gpt4 book ai didi

reactjs - 渲染时的 react 显示先前的状态值

转载 作者:行者123 更新时间:2023-12-03 13:42:08 24 4
gpt4 key购买 nike

我是 ReactJS 的初学者,刚刚开始学习并开始编写猜测数字的代码,但猜测计数显示不同的值。 {this.state.attempts} 保存编号。用户尝试找到答案以显示正确值所需的次数。但是 {this.state.result} 显示每次点击的结果,但如果用户找到答案,它会显示之前的状态。我想知道这是怎么发生的。这是因为它不在 render() 下吗?

import React, { Component } from 'react';

export default class NoLifeCycComps extends Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
this.checkValue = this.checkValue.bind(this);
this.updateInput = this.updateInput.bind(this);
}

randNum(){
return Math.floor((Math.random() * 100) + 1);
}

getInitialState(){
return {
num: this.randNum(),
inputValue: '',
attempts: 0,
result: '',
reset : false
}
}

reset() {
this.setState(this.getInitialState());
}

checkValue() {
this.setState((prevState) => {
return { attempts: prevState.attempts + 1 }
});
if (this.state.inputValue > this.state.num) {
this.state.result = "higher";
} else if (this.state.inputValue < this.state.num) {
this.state.result = "lesser";
} else if (this.state.inputValue == this.state.num) {
this.state.result = "you found it on " + this.state.attempts + "attempt(s)";
this.state.reset = true;
}
}


updateInput(e) {
this.setState({ inputValue: e.target.value })
}

render() {

return (
<div className = "numberGuess">
<h3> Guess the number </h3>
<input type = "text" value = { this.state.inputValue } onChange = { this.updateInput }/>

{this.state.reset ? <button onClick = { () => this.reset() }> start again! </button> : <button onClick = { () => this.checkValue() }> click </button>}
No.of Attempts took: { this.state.attempts } <br/>
<span> { this.state.result } </span>
</div>
);
}
}

最佳答案

setState 是一个异步函数。 setState 的下一个语句可能没有更新的状态值。我还在您的代码中发现了突变状态更新。请避免突变更新。您应该使用 setState

更新所有状态

示例

  checkValue() {
let {
attempts,
inputValue,
num,
result,
reset
} = this.state;

attempts++;

if (inputValue > num) {
result = "higher";
} else if (inputValue < num) {
result = "lesser";
} else if (inputValue == num) {
result = "you found it on " + attempts + "attempt(s)";
reset = true;
}

this.setState({
attempts,
result,
reset
});
}

在这个例子中,我们将现有的状态值存储在变量中并对其进行操作。在计算结束时,我们更新一次状态。

关于reactjs - 渲染时的 react 显示先前的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50985314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com