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

React JS中shuffle调用前定义的正确选项常量值持续变化问题求助

问题核心原因

你的问题出在两个点:

  • 你使用的shuffle是原地修改数组的实现,操作时会直接修改传入的数组本身
  • JavaScript中数组是引用类型,代码里const optionsArray = mcqData.m_alternatives只是给原数组起了个别名,并没有生成新数组,你调用shuffle(optionsArray)的时候,等于直接把mcqData.m_alternatives原数组给打乱了。

第一次渲染完成后,原数组里的第一个元素已经不是最初的正确答案了,后续组件只要触发重渲染,你重新取的mcqData.m_alternatives[0]自然就会不断变化。


修复方案

  1. 传入shuffle之前先给原数组创建浅拷贝,操作拷贝出来的新数组,避免修改原数据:
// 用展开运算符生成新数组
const optionsArray = [...mcqData.m_alternatives]
const shuffledArray = shuffle(optionsArray)
  1. 如果要避免组件重渲染时选项反复打乱,可以用useMemo缓存打乱后的结果,保证同一次页面加载过程中选项顺序固定。

完整修改后代码

import React, { useMemo } from 'react';
import mcqContent from './mcq-content';

const MCQPage = ({match}) =>{
    const reqUrl = match.params.name;
    const mcqData = mcqContent.find(mcqData => mcqData.m_slug === reqUrl);
    const correctMcq = mcqData.m_alternatives[0];
    // 缓存打乱后的选项,仅mcqData变化时重新生成,同时操作数组副本不修改原数据
    const shuffledArray = useMemo(() => {
      const optionsArray = [...mcqData.m_alternatives]
      return shuffle(optionsArray)
    }, [mcqData])

    return (
    <>
        <h1>{mcqData.m_title}</h1><br/>
        <h3>{mcqData.m_question}</h3>
        {shuffledArray.map((paragraph, key) => (
            <p key={key}>{paragraph}</p>
            ))}
        <h4>Answer: {correctMcq}</h4>
    </>
    );
};
export default MCQPage; 

function shuffle(array) {
    let currentIndex = array.length,  randomIndex;
    while (currentIndex !== 0) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
      [array[currentIndex], array[randomIndex]] = [
        array[randomIndex], array[currentIndex]];
    }
    return array;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:24:03