javascript 如何在React中将数据从子组件发送到父组件中的特定数组

jvidinwx  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(91)

当我点击一个答案按钮时,我想将该数据发送到相关数组,但问题是它将数据发送到所有数组,当我点击另一个按钮时,它只是将selectedAnswer替换为单击的按钮(下图将解释有关问题的很多内容)
这是我的代码
Quiz.js(子组件)

const answerButtons = decodedAnswers.map (decodedAnswer => (
  <button 
  id={decodedAnswer}
  key={decodedAnswer}
  onClick={()=>props.selectAnswer(decodedAnswer)}
  >

     {decodedAnswer}

  </button>

App.js(父组件)

async function fetchData () {
    const response = await fetch (apiURL)
    const data = await response.json ()

    setQuestions (data.results)
  }
  

  function selectAnswer(questionId, answer) {
    setQuestions((prevQuestions) =>
      prevQuestions.map((data) =>
        data.id === questionId ? { ...data, selectedAnswer: answer } : data
      )
    );
  }  

  const quizElements = questions.map (quiz => (
    <Quiz 
      question={quiz.question}  
      key={quiz.question}
      correctAnswer={quiz.correct_answer}
      incorrectAnswers={quiz.incorrect_answers}
      selectAnswer={(answer) => selectAnswer(quiz.id, answer)}
    />
  ))

  function handleClick () {
    console.log (questions)
  }
  const checkAnswers = <button onClick={handleClick}>Check Answers</button>

所以如果你能帮我我会很感激的
在紧急情况下,这里是完整的代码Quiz.js(子组件)

import React from "react";
import { useState, useEffect, useMemo } from "react";
import './style.css'
const he = require('he');

function Quiz (props) {
    const [shuffledAnswers, setShuffledAnswers] = useState ([])
    const [chosenAnswer, setChosenAnswer] = useState (null)

    const answers = [...props.incorrectAnswers]
    const correctAnswer = props.correctAnswer

    useEffect (()=> {
        const shuffled = [...answers]
        const ranNumForAnswerMix = 
                     Math.floor(Math.random() * (answers.length + 1))
        answers.splice (ranNumForAnswerMix, 0, correctAnswer)
        setShuffledAnswers (shuffled)
    }, [])    

    const decodedQuestion = typeof 
                props.question === 'string' ? he.decode(props.question) : props.question;

    const decodedCorrectAnswer = 
                typeof correctAnswer === 'string' ? he.decode(correctAnswer) : correctAnswer;

    const decodedAnswers = shuffledAnswers.map (answer => (
        typeof answer === 'string' ? he.decode(answer) : (answer)
    ));

    const answerButtons = decodedAnswers.map (decodedAnswer => (
        <button 
          id={decodedAnswer}
          key={decodedAnswer}
          onClick={()=>props.selectAnswer(decodedAnswer)}
        >

            {decodedAnswer}

        </button>
    ))
    

    return (
        <>
        <div className="quiz-parent">
            <div>
               <div>                        
                    <p>{decodedQuestion}</p>
                    <p>answer: {decodedCorrectAnswer} </p>
                    {answerButtons}
                </div>
            </div>
            </div>
        </>
    )

}

export default Quiz

App.js(父组件)

import React from 'react';
import './App.css';
import Start from './components/Start';
import Quiz from './components/Quiz';
import { useState, useEffect } from 'react';

function App() {

  const [isStartScreenShowing, setIsStartScreenShowing] = useState (true)
  const [questions, setQuestions] = useState ([])

  const apiURL = 
          'https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple'

  
  function toggleStartScreen () {
      setIsStartScreenShowing (false)
      fetchData ()
  }

  async function fetchData () {
    const response = await fetch (apiURL)
    const data = await response.json ()

    setQuestions (data.results)
  }
  

  function selectAnswer(questionId, answer) {
    setQuestions((prevQuestions) =>
      prevQuestions.map((data) =>
        data.id === questionId ? { ...data, selectedAnswer: answer } : data
      )
    );
  }  

  const quizElements = questions.map (quiz => (
    <Quiz 
      question={quiz.question}  
      key={quiz.question}
      correctAnswer={quiz.correct_answer}
      incorrectAnswers={quiz.incorrect_answers}
      selectAnswer={(answer) => selectAnswer(quiz.id, answer)}
    />
  ))

  function handleClick () {
    console.log (questions)
  }

   

  const checkAnswers = <button onClick={handleClick}>Check Answers</button>
  

  
  return (
    <div className="App">

        { isStartScreenShowing &&
          <Start 
            isStartScreenShowing={isStartScreenShowing}
            toggleStartScreen={toggleStartScreen} 
          />
        }

        { isStartScreenShowing !== true &&
        <>
          {quizElements}
          {checkAnswers}
        </>
        }

    </div>
  );
}

export default App;
ulmd4ohb

ulmd4ohb1#

是否确定问题对象具有id?在你附上的屏幕截图中,没有id的值。如果id不在对象中,它将是undefined,所以所有的id都是相同的,因此所有的问题都将被更新。

相关问题