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

React/Chart.js中数组最后一题未渲染且未计入分数的问题排查

问题原因与修复方案

问题根源

渲染条件逻辑错误:当前代码在currentQuestion === questions.length - 1(即索引23,对应第24个问题)时直接显示雷达图,跳过了最后一个问题的展示和回答流程。因为currentQuestion从0开始计数,当它等于23时,本应展示第24个问题,而不是直接结束问卷。

修复步骤

将渲染判断条件从currentQuestion === questions.length - 1修改为currentQuestion >= questions.length,确保只有当用户回答完所有24个问题(currentQuestion变为24)后,才显示结果图表。

修改后,currentQuestion取值0到23时都会展示对应问题,回答完第24个问题后,currentQuestion变为24,触发图表渲染,同时最后一个问题的回答会被正常计入分数计算。

修改后的核心代码片段

return (
  <div>
    {currentQuestion >= questions.length ? (
      <Radar
        data={chartData}
        options={{
          scale: {
            beginAtZero: true,
            max: 6,
            min: 0,
            ticks: {
              stepSize: 1,
            }
          }
        }}/>
    ) : (
      <div>
        <p>In meinem direkten Arbeitsumfeld .../ In der Gruppe in der ich mich wohl fühle ... <br></br> {questions[currentQuestion]}</p>
        {options.map((option) => (
          <button
            key={option.value}
            onClick={() => {
              setResponses(
                responses.map((response, index) => {
                  if (index === currentQuestion) {
                    return option.score;
                  }
                  return response;
                })
              );
              setCurrentQuestion(currentQuestion + 1);
            }}
          >
            {option.text}
          </button>
        ))}
      </div>
    )}
  </div>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:52:37