使用React更改数字的功能无法正常工作

问题描述 投票:1回答:1

我试图通过单击按钮来更改存储在变量中的数字,但是第一次单击按钮时,它不会更改变量的值,但第二个变量的值。我以1为增量更改数字,所以当我点击按钮时,它的currentNumber += 1和我运行一个console.log,看它是否会改变。我第一次点击它,它会打印出默认值,第二次点击它就是它实际发生变化的时候,它会搞乱我代码的预期功能。我正在使用React。

constructor(props) {
	    super(props);
        this.state = {
            currentSize: parseInt(this.props.size),
            min: 4,
            max: 40,
        }
    };
    
    
increaseSize(){
        this.setState({currentSize: this.state.currentSize + 1}, function(){
            if(this.state.currentSize >= this.state.max){
                this.state.currentSize = this.state.max;
                this.state.isRed = true;
            } else if(this.state.currentSize < this.state.max){
                this.state.isRed = false;
            }
        });
        console.log(this.state.currentSize);
    };
    
render() {
        var isBold = this.state.bold ? 'normal' : 'bold';
        var currentSize = this.state.currentSize;
        var textColor = this.state.isRed ? 'red' : 'black';

        return(
               <div>
               <button id="decreaseButton" hidden='true' onClick={this.decreaseSize.bind(this)}>-</button>
               <span id="fontSizeSpan" hidden='true' style={{color: textColor}}>{currentSize}</span>
               <button id="increaseButton" hidden='true' onClick={this.increaseSize.bind(this)}>+</button>
               <span id="textSpan" style={{fontWeight: isBold, fontSize: currentSize}} onClick={this.showElements.bind(this)}>{this.props.text}</span>
               </div>
        );
    }

然后显示变量中的数字,但显示的数字与变量内的数字不同

enter image description here

正如您在图片中看到的那样,显示的数字是26,但变量是25。

此外,您可以看到我为计数器设置了最小值和最大值。当它达到任一值时,它会在显示屏中进一步显示,但不会在控制台中显示。所以在显示器中它停在3和41但在控制台中它停在4和40。

我究竟做错了什么?

编辑:默认值为16,这是我第一次点击按钮时打印到控制台的原因,这就是它无法正常工作的原因。

javascript reactjs dom
1个回答
0
投票

使用setState()的功能版本来获取prev状态值 - 因为React异步处理状态更改,在设置它们时无法保证它们的值;这也是你使用console.log的原因。取而代之的是:

increaseSize(){
const aboveMax = this.state.currentSize >= this.state.max;

this.setState( prevState => ({
    currentSize: aboveMax ? prevState.max : prevState.currentSize + 1,
    isRed: aboveMax
})
, () => console.log(this.state.currentSize) );
};

或者,如果您不想使用render()回调函数,请将控制台语句移至setState()方法。

https://reactjs.org/docs/react-component.html#setstate

别忘了在你的构造函数中设置isRed :)

© www.soinside.com 2019 - 2024. All rights reserved.