Я новичок в React Js, и для своего проекта я начал писать онлайн-тест с помощью React JS.
- Я показываю результат теста и правильные ответы в конце викторина. Я рисую диаграмму ap ie, показывающую количество правильных и неправильных ответов. Я хочу порекомендовать студентам сказать, в какой категории задач они справились хорошо? Я не понимаю, как извлечь балл ученика в реальном времени и передать его в файл для построения графика? Данные об оценке необходимо передать из «Викторина. js» в «График. js»
Вот мой банк вопросов. js файл
const qBank = [
{
id: 0,
question:
"The following formula will produce: Fn = Fn-1 + Fn-2 ? ",
options: ["Armstrong Number", "Fibonacci Series", "Prime Number", "Euler Number"],
answer: "Fibonacci Series",
incorrect: ["Armstrong Number","Prime Number", "Euler Number"],
category: "Algorithm",
},
{
id: 1,
question:"Which of the following searching techniques do not require the data to be in sorted form?",
options: ["Binary Search", "Interpolation Search", "Linear Search ", "All of the above"],
answer: "Binary Search",
incorrect: ["Interpolation Search", "Linear Search ", "All of the above"],
category: "Algorithm",
},
{
id: 2,
question:
"Which symbol is used to represent an input/output in a systems flowchart?? ",
options: ["Diamond", "Arrow", "Parallelogram", "Circle"],
answer: "Parallelogram",
incorrect: ["Diamond", "Arrow ", "Circle"],
category: "Flowchart",
},
{
id: 3,
question:
"What is the correct order of occurrence in a system flowchart? ",
options: ["Input, output, feedback, process", "Input, process, output, feedback", "Feedback, input, output, process", "Input, output, process, feedback"],
answer: "Input, process, output, feedback",
incorrect: ["Input, output, feedback, process","Feedback, input, output, process", "Input, output, process, feedback"],
category: "Flowchart",
},
{
id: 4,
question:
"What identifier sets a variable as true or false? ",
options: ["double", "char", "String", "boolean"],
answer: "boolean",
incorrect: ["double", "char ", "String"],
category: "Programming",
},
{
id: 5,
question:
"What class expose methods such as power to, Pi, square root, and cube root? ",
options: ["Calc", "Math", "Utils", "String"],
answer: "Math",
incorrect: ["Calc", "Utils ", "String"],
category: "Programming",
},
];
export default qBank;
График. js файл
import React, {useState, useEffect} from 'react';
import {Pie} from 'react-chartjs-2'
import { Link } from 'react-router-dom';
const PieChart = ({score}) =>
{
// this.props.navigation.getParam(score)
const [chartData,setChartData]= useState({})
const chart = () =>{
setChartData({
labels: ['Correct Answers', 'Incorrect Answers'],
datasets:[
{
label: 'statistical chart',
// data: [score,2],
data:[4,2],
backgroundColor: ['rgba(255,99,132,1)',
'rgba(255,205,86,1)'],
borderWidth: 4
}
]
})
}
useEffect(()=>
{
chart()
},[])
return(
<div>
<div style={{width:'1000px', height:'1000px',textAlign:"center",marginLeft:'250px'}}>
<Pie data={chartData}/>
<Link to="/Test" style={{textAlign:"center"}}>Attempt test again</Link>
</div>
</div>
)
}
export default PieChart;
Викторина. js файл
импорт React, {Component} из 'react'; import './style.css' импортировать банк вопросов из './QuestionBank.js'; импортировать {P ie} из 'response-chart js -2'; импортировать PieChart из './Graph';
class Quiz extends Component{
constructor(props){
super(props)
this.state={
userAnswer:null,
currentIndex:0,
options: [],
quizEnd: false,
score:0,
disabled:true,
}
}
loadQuiz=()=>{
const{currentIndex}=this.state;
this.setState(()=>{
return{
question:QuestionBank[currentIndex].question,
options:QuestionBank[currentIndex].options,
answer:QuestionBank[currentIndex].answer
}
}
)
}
nextQuestionHandler=()=>{
const{userAnswer,answer,score}=this.state
if(userAnswer===answer){
this.setState(
{
score:score+1
}
)
}
this.setState({
currentIndex: this.state.currentIndex +1,
userAnswer: null
})
}
previosQuestionHandler=()=>{
// const{userAnswer}=this.state
this.setState({
currentIndex: this.state.currentIndex -1,
userAnswer: null
})
}
componentDidMount(){
this.loadQuiz();
}
checkAnswer = answer =>(
this.setState({
userAnswer: answer,
disabled: false,
})
)
finishHandler=()=>{
const{userAnswer,answer,score}=this.state
if(userAnswer===answer){
this.setState({
score: score+1
})
}
if (this.state.currentIndex===QuestionBank.length-1){
this.setState(
{
quizEnd:true
}
)
}
}
attemptAnotherTry=()=>
{
this.loadQuiz();
this.setState(
{
userAnswer:null,
currentIndex:0,
options: [],
quizEnd: false,
score:0,
disabled:true,
}
)
}
checkStatistics= (props) =>
{
const{score}=this.state
this.setState(
{
score:score
}
)
// this.props.navigation.navigate("/Graph", {score })
window.location.href = "/Graph";
// <PieChart click={this.props.PieChart}></PieChart>
// <Graph click={this.state.score}/>
}
componentDidUpdate(prevProps, prevState){
const{currentIndex}= this.state;
if(this.state.currentIndex !== prevState.currentIndex){
this.setState(()=>{
return{
disabled:true,
question:QuestionBank[currentIndex].question,
options:QuestionBank[currentIndex].options,
answer:QuestionBank[currentIndex].answer
}
}
)
}
}
render()
{
const {question,options,currentIndex,userAnswer,quizEnd}= this.state
if(quizEnd){
return(
<div className="containerBox">
<h1> Game Over. Final score is {this.state.score} points</h1>
<p> The correct answers for the quiz are</p>
<ul>
{QuestionBank.map((item,index) => (
<li className='options'
key={index}>
{item.answer}
</li>
))}
</ul>
{currentIndex===QuestionBank.length-1 &&
<button className="attemptButton" onClick={this.attemptAnotherTry} disabled= {this.state.disabled}>
Retest?
</button>
}
{currentIndex===QuestionBank.length-1 &&
<button onClick={this.checkStatistics.bind(this)}>Check Statistics</button>
}
</div>
)
}
return(
<div className="containerBox">
<div className="title">Quiz </div>
<h2>{question}</h2>
<span>{`Question ${currentIndex+1} of ${QuestionBank.length}`}</span>
{
options.map(option=>
<p key={option.id} className={`options ${userAnswer===option?"selected": null}`}
onClick={()=> this.checkAnswer(option) }
>
{option}
</p>
)
}
{currentIndex < QuestionBank.length-1 &&
<button disabled ={ this.state.disabled} onClick={this.nextQuestionHandler}>
Next Question
</button>}
{currentIndex < QuestionBank.length-1 && currentIndex >0 &&
<button onClick={this.previosQuestionHandler} className="previousQuestion">
Previous Question
</button>}
{currentIndex===QuestionBank.length-1 &&
<button onClick= {this.finishHandler} disabled= {this.state.disabled}>
Finish
</button>
}
</div>
)
}
}
export default Quiz;
Для предоставления рекомендаций я сохранил категорию в файле' QuestionBank. js ', где хранятся вопросы и варианты. Я сохранил 6 вопросов (по 2 вопроса в каждой категории, т.е. алгоритмы, блок-схемы и программы). Здесь мне нужно получить категорию и дать рекомендацию, например ... вы набрали максимум в категории алгоритма, вы набрали минимум в блок-схеме, так что сосредоточьтесь на этом и так далее ... вы набрали средний балл в программировании Но я не понимаю, как получить категорию каждого вопроса и использовать его для предложения?