如何在React(useState)中实现同一按钮点击增计数并回退至上一状态
React useState 实现计数加减切换功能
实现该功能的核心逻辑是额外存储上一次的计数值,同时标记按钮的当前操作状态,根据状态执行加1或回退逻辑,具体实现如下:
单步切换实现(点击一次加1,再次点击回退,循环切换)
import { useState } from 'react'; function ToggleCounter() { const [count, setCount] = useState(0); // 存储回退需要用到的上一次计数值 const [lastCount, setLastCount] = useState(0); // 标记当前是否已执行加1操作 const [isIncremented, setIsIncremented] = useState(false); const handleBtnClick = () => { if (!isIncremented) { // 执行加1操作前先存储当前值 setLastCount(count); setCount(prev => prev + 1); setIsIncremented(true); return; } // 执行回退操作,恢复到上一次的计数值 setCount(lastCount); setIsIncremented(false); }; return ( <div> <p>当前计数:{count}</p> <button onClick={handleBtnClick}> {isIncremented ? '回退计数' : '计数加1'} </button> </div> ); } export default ToggleCounter;
多步回退实现(支持连续多次加1,再逐次回退到之前的任意状态)
如果需要支持多次累加后逐次回退,可以用数组存储计数历史栈,通过下标控制当前展示的计数值:
import { useState } from 'react'; function HistoryCounter() { // 存储所有历史计数值的栈 const [countHistory, setCountHistory] = useState([0]); // 当前展示的计数对应的历史栈下标 const [currentStep, setCurrentStep] = useState(0); const [isIncrementMode, setIsIncrementMode] = useState(true); const handleBtnClick = () => { if (isIncrementMode) { const newCount = countHistory[currentStep] + 1; // 若当前不是在历史栈末尾,先截断后面的无效历史 const newHistory = countHistory.slice(0, currentStep + 1).concat(newCount); setCountHistory(newHistory); setCurrentStep(prev => prev + 1); setIsIncrementMode(false); return; } // 回退操作,禁止下标小于0 if (currentStep > 0) { setCurrentStep(prev => prev - 1); } setIsIncrementMode(true); }; return ( <div> <p>当前计数:{countHistory[currentStep]}</p> <button onClick={handleBtnClick}> {isIncrementMode ? '计数加1' : '回退上一步'} </button> </div> ); } export default HistoryCounter;
内容的提问来源于stack exchange,提问作者Siddhant Prateek
相关产品推荐
相关产品推荐

