You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit中markAsKnown函数状态更新延迟问题求助

问题:Redux Toolkit中markAsKnown状态更新延迟,需二次点击才生效

问题描述

刚完成React课程后开发首个大型项目,遇到Redux Toolkit中markAsKnown函数的状态更新问题。期望点击该函数后能立即更新state.maxIndex = state.technologyArray.length,但实际需第二次点击才生效。这导致页面剩余题目数量显示异常,且索引抽取可能超出数组长度。

问题根源

  1. markAsKnown逻辑顺序错误:当前代码先过滤未标记的题目数组、更新maxIndex,再标记当前题目为known。这意味着本次更新的maxIndex仍包含刚被标记的题目,要等下一次调用过滤逻辑时才会排除,导致第一次点击后maxIndex未正确更新。
  2. 组件dispatch顺序错误:点击按钮时先调用getRandomIndex(基于旧的maxIndex生成索引),再调用markAsKnown,不仅会导致索引可能指向已标记的题目,还加剧了状态更新的延迟问题。
  3. initialState拼写错误:technolog: 'JavaScript',ntechnologArray: [], 存在拼写错误,应改为technology: 'JavaScript', technologyArray: [],,否则会导致状态字段不匹配。

解决方案

1. 修正markAsKnown的逻辑顺序

先标记当前题目为known,再重新过滤未标记的题目数组并更新maxIndex,确保本次更新就能得到正确的剩余题目数量:

markAsKnown: (state) => {
  // 先标记当前题目为已掌握
  if (state.technologyArray[state.index]) {
    state.technologyArray[state.index].known = true;
  }
  // 重新过滤未掌握的题目数组,更新maxIndex
  state.technologyArray = state.questions.filter(
    (tech) => state.technology === tech.tech && tech.known === false
  );
  state.maxIndex = state.technologyArray.length;
  if (state.maxIndex === 0) console.log('Koniec pytań');
},

2. 修正组件中的dispatch顺序

先调用markAsKnown更新状态,再调用getRandomIndex基于新的maxIndex生成随机索引:

<BsCheckCircle
  onClick={() => {
    dispatch(markAsKnown());
    dispatch(getRandomIndex());
  }}
  className="h-14 w-14 hover:text-teal-500 transition-all hover:scale-105 active:scale-95"
/>

3. 修正initialState的拼写错误

const initialState = {
  maxIndex: 10, // chwilowo
  index: 0,
  questions: QuestionsData,
  technology: 'JavaScript',
  technologyArray: [],
};

说明

  • 先标记题目再过滤数组,确保maxIndex在本次action中就更新为排除已标记题目后的长度,解决二次点击才生效的问题。
  • 调整dispatch顺序后,新的随机索引会基于更新后的maxIndex生成,避免索引超出数组长度的情况。
  • 修正拼写错误保证状态字段的一致性,避免潜在的状态匹配问题。

内容的提问来源于stack exchange,提问作者Xcut1on

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:55:28