简体   繁体   English

反应对象和数组

[英]React objects and arrays

I was trying to match the answers on click based on the correct answer provided in the json, but since i was running a map function to return the data, although i was able to get the value of clicked button from the object but not able to match it with the correct answer with the clicked answer.我试图根据 json 中提供的正确答案匹配点击时的答案,但由于我正在运行地图函数来返回数据,尽管我能够从对象中获取单击按钮的值但无法将其与正确答案与点击的答案相匹配。

below is my code下面是我的代码

quiz测验

import React, { useState } from "react";
import quizData from "../data/quizData.json";

export default function Quiz() {
  const [value, setValue] = useState(quizData);

  function handleClick(e) {
    let answer = value.quiz_questions[0].answer;
    if (answer === e.target.value) {
      alert("Correct Answer");
    } else {
      alert("Please choose the correct answer");
    }
    console.log(e.target.value);
    console.log(answer);
  }

  return (
    <div>
      {value.quiz_questions.map((quiz) => {
        return (
          <div key={quiz.id}>
            <p>{quiz.instruction_text}</p>
            {quiz.answer_options.map((btn, index) => {
              return (
                <button key={index} onClick={handleClick} value={btn}>
                  {btn}
                </button>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

quizData测验数据

{
  "quiz_questions": [
    {
      "id": 1,
      "instruction_text": "How many continents are there on Planet Earth?",
      "answer_options": ["5", "6", "7", "8"],
      "answer": "7"
    },
    {
      "id": 2,
      "instruction_text": "What's your favorite number?",
      "answer_options": ["1", "2", "3", "4"],
      "answer": "4"
    }
  ]
}

The above code will work for 1st question as i was hardcoding the answer for the 1st object in the array, is there any chance that we can loop through the array and set it with the clicked answer?上面的代码适用于第一个问题,因为我正在对数组中的第一个对象的答案进行硬编码,我们是否有机会遍历数组并使用单击的答案进行设置?

You need to find first object:您需要找到第一个对象:

let answer = value.quiz_questions.find((data) => data.id == id)?.answer;

complete handleClick function logic:完整的handleClick函数逻辑:

function handleClick(btnValue, id) {
    let answer = value.quiz_questions.find((data) => data.id == id).answer;
    if (answer === btnValue) {
      alert("Correct Answer");
    } else {
      alert("Please choose the correct answer");
    }
    console.log(answer);
  }

Here is complete code:这是完整的代码:

import React, { useState } from "react";
import "./styles.css";

const quizData = {
  quiz_questions: [
    {
      id: 1,
      instruction_text: "How many continents are there on Planet Earth?",
      answer_options: ["5", "6", "7", "8"],
      answer: "7"
    },
    {
      id: 2,
      instruction_text: "What's your favorite number?",
      answer_options: ["1", "2", "3", "4"],
      answer: "4"
    }
  ]
};
function Quiz() {
  const [value, setValue] = useState(quizData);

  function handleClick(btnValue, id) {
    let answer = value.quiz_questions.find((data) => data.id == id).answer;
    if (answer === btnValue) {
      alert("Correct Answer");
    } else {
      alert("Please choose the correct answer");
    }
    console.log(answer);
  }

  return (
    <div>
      {value.quiz_questions.map((quiz) => {
        return (
          <div key={quiz.id}>
            <p>{quiz.instruction_text}</p>
            {quiz.answer_options.map((btn, index) => {
              return (
                <button
                  key={index}
                  onClick={(e) => handleClick(btn, quiz.id)}
                  value={btn}
                >
                  {btn}
                </button>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Quiz />
    </div>
  );
}


Here is the demo: https://codesandbox.io/s/hungry-elbakyan-3qm57?file=/src/App.js:0-1429这是演示: https : //codesandbox.io/s/hungry-elbakyan-3qm57?file=/ src/App.js: 0-1429

You can pass the question id in the handleClick method and use that to find out the correct answer.您可以在 handleClick 方法中传递问题 id 并使用它来找出正确答案。 Moreover, instead of passing event, you directly pass the selected answer as well.此外,您也可以直接传递选定的答案,而不是传递事件。

export default function Quiz() {
  const [value, setValue] = useState(quizData);

  function handleClick(quesId, selectedAnswer) {
    let answer = value.quiz_questions.filter(question => question.id === quesId)[0].answer;
    if (answer === selectedAnswer) {
      alert("Correct Answer");
    } else {
      alert("Please choose the correct answer");
    }
    console.log(selectedAnswer);
    console.log(answer);
  }

  return (
    <div>
      {value.quiz_questions.map((quiz) => {
        return (
          <div key={quiz.id}>
            <p>{quiz.instruction_text}</p>
            {quiz.answer_options.map((btn, index) => {
              return (
                <button key={index} onClick={() => handleClick(quiz.id, btn)} value={btn}>
                  {btn}
                </button>
              );
            })}
          </div>
        );
      })}
    </div>
  );
}

You may try the modified version of your source code(esp. the one with map()), and you'll note that onLoad event has been attached to help in capturing the answer options upon loading of the document, then the handleClick function will pick up from there.您可以尝试修改后的源代码版本(尤其是带有 map() 的版本),您会注意到 onLoad 事件已附加以帮助在加载文档时捕获答案选项,然后 handleClick 函数将从那里接。 That being said, the following is the modified version of the source code beginning after inside return():话虽如此,以下是从内部 return() 开始的源代码的修改版本:

    {value.quiz_questions.map((quiz) => {
            return (
              <div key={quiz.id}>
                <p>{quiz.instruction_text}</p>
                {quiz.answer_options.map((btn, index) => {
                  return (
                    <button key={index} onLoad={() => setValue(btn)} onClick={handleClick} value={btn}>
                      {btn}
                    </button>
                  );
                })}
              </div>
            );
    })}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM