React组件重渲染时状态丢失:Quiz应用问题切换异常
解决React测验组件状态重置问题
你的问题出在handleQuestionAnswer回调的状态更新逻辑和useCallback的依赖处理上:
- 原代码里直接用
selectedQuestion + 1更新状态,但useCallback的依赖数组没加selectedQuestion,导致回调一直引用初始的selectedQuestion值(0),第二次调用时还是会把状态设为1,看起来像是状态被重置。 - 用
map遍历所有题目再判断索引的写法冗余,没必要遍历全部元素。
修改后的代码
function Quizz() { const [selectedQuestion, setSelectedQuestion] = useState(0); const handleQuestionAnswer = useCallback((isRejection) => { // 用函数式更新获取最新状态值,避免依赖外部变量 setSelectedQuestion(prev => prev + 1); }, [setSelectedQuestion]); // 直接通过索引取当前题目,无需遍历 const currentQuestion = QuizzData.questions[selectedQuestion]; // 防止索引越界(比如答完所有题目后) if (!currentQuestion) return <div>测验已完成</div>; return ( <Question data={currentQuestion} clickCallback={handleQuestionAnswer} key={selectedQuestion} /> ); }
关键修改点
- 函数式状态更新:把
setSelectedQuestion(selectedQuestion + 1)改成setSelectedQuestion(prev => prev + 1),这样不管回调什么时候执行,都能拿到最新的状态值,不需要把selectedQuestion加到useCallback的依赖数组里,避免闭包陷阱。 - 优化渲染逻辑:直接通过
selectedQuestion索引从数组中获取当前题目,比遍历所有题目更高效,同时增加了空值判断防止报错。 - 保持key的正确性:用
selectedQuestion作为组件的key,确保每次切换题目时React能正确识别组件更新,避免不必要的重渲染或状态异常。
补充:异步获取题目时的处理
如果题目是从API异步获取的,记得用useState保存接口返回的数据,不要直接用全局变量,同时在更新状态时判断是否超出题目数量:
function Quizz() { const [questions, setQuestions] = useState([]); const [selectedQuestion, setSelectedQuestion] = useState(0); // 发起API请求获取题目 useEffect(() => { fetch('/your-api-url') .then(res => res.json()) .then(data => setQuestions(data)); }, []); const handleQuestionAnswer = useCallback((isRejection) => { setSelectedQuestion(prev => { // 防止超出题目总数,避免索引越界 if (prev + 1 >= questions.length) return prev; return prev + 1; }); }, [questions.length]); // 加载状态处理 if (questions.length === 0) return <div>加载中...</div>; const currentQuestion = questions[selectedQuestion]; return ( <Question data={currentQuestion} clickCallback={handleQuestionAnswer} key={selectedQuestion} /> ); }
内容的提问来源于stack exchange,提问作者Rui Rego
相关产品推荐
相关产品推荐

