javascript - 以随机顺序渲染数组 React Js
问题描述
我是 React Js 初学者。我正在创建一个 MCQ 门户并希望以随机顺序显示 mcqs 选项。
- 现在我正在使用
.js
文件来存储数据,但后来计划转移到 MongoDB。 - 我正在使用 URL 参数来检索特定的 MCQ。有没有办法洗牌?
这是代码
import React 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];
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
const optionsArray = mcqData.m_alternatives
const shuffledArray = shuffle(optionsArray)
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;
这是 MCQ 内容文件
const mcqs = [
{
"_id":1,
"m_title":"Which company is the most valueable in the world?",
"m_slug":"which-company-is-the-most-valueable",
"m_question":"Which company is the most valueable in the world?",
"m_alternatives":["Apple","Google","Microsoft"],
"m_number":"Gen-Know-1",
"m_subject":"General Knowledge",
},
];
export default mcqs;
解决方案
推荐阅读
- php-curl - Coinimp http api 撤回
- c++ - 检查多图C++中是否已经存在值
- javascript - window.XXX = require(YYY) VS const {XXX} = require(YYY):使用哪个?
- google-sheets - Google表格中INDIRECT内的COUNTIF
- c# - .net 核心中的逆变性如何与 Func 委托一起使用
- python - 将 N 个矩阵相乘 - 符号计算
- hyperledger-fabric - 在 Hyperledger Fabric 中的 Channel MSP 中识别客户端
- robotframework - 如何在 Windows 中使用 Robot Framework 显式打开 excel 文件
- python - 我可以让 Anaconda 导航器在 pypi 上查看包吗?
- perl - 如何创建仅在一个请求期间全局的“全局”范围变量?