繁体   English   中英

如何将数据从 React 组件传递到主文件?

[英]How can I pass data from a React component to main file?

我在将数据从组件传递到主文件时遇到问题。 它是一个基本的测验应用程序,从 api 获取测验对象并将数据传递给“问题”组件。 在主文件中,我有分数 state 来决定有多少答案是正确的。 但是,当单击应答按钮时,应用程序会看到组件中的值。 我想通过 state 匹配答案值和正确答案并增加分数。 这是问题组件和主文件。

export default function Question(props) {

const [flag,setFlag] = React.useState(true)

// TOGGLE BUTTON BACKGROUND COLOR WHEN BTN CLICKED
function toggleBtnBgColor(btn) {
    if(flag) {
        btn.target.classList.toggle("dark-bg-color")
        setFlag(false)
    }
}

return (
    <>
        <div className="question" key={props.index}>{props.question}</div>
            {props.answers.map((answer,index)=> {
                return (
                    <button key={index} onClick={toggleBtnBgColor} className="answer-button">{answer}</button>
                )
        })}
        <hr></hr>
    </>
)

}

主文件;

const [data, setData] = React.useState([])
const [score, setScore] = React.useState(0)
const [startAgain, setStartAgain] = React.useState(false)

// FETCH QUIZ DATA FROM API
const fetchData = async () => {
    await fetch("https://opentdb.com/api.php?amount=5&type=multiple")
    .then((response) => response.json())
    .then((data) => setData(data.results))
}

React.useEffect(()=> {
    fetchData()
},[])

// SHUFFLE ALGORITHM TO USE LATER
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;
}

// RENDER QUESTIONS
const questionElements = data.map((question, index) => {
    // ANSWERS ARRAY AND SHUFFLE
    let answers = [...question.incorrect_answers,question.correct_answer]
    shuffle(answers)

    return (
        <Question key={index} index={index} question={question.question} answers={answers}/>
    )
})

// CALCULATE FINAL SCORE WHEN CHECK BTN CLICKED
function calcScore() {
    for(let question of questionElements) {
        console.log(question.calcScore)
    }
    setStartAgain(true)
}

return (
    <div className="question-container">
        {questionElements}
        <p>{startAgain && ("Your score is "+ score +"/5")}</p>
        <button onClick={calcScore} className="check-button">{!startAgain ? "Check Answers" : "Restart Quiz"}</button>
    </div>
)

检查一下,我们将 function 传递给接收答案和索引的问题。 父级将更新一个包含所有答案的数组

https://codesandbox.io/s/black-cdn-p6lo5v?file=/src/App.js

const setAnswer = (index, answer) => {
  const newAnswers = [...answers];
  newAnswers[index] = answer;
  setAnswers(newAnswers);
};


// RENDER QUESTIONS
const questionElements = data.map((question, index) => {
  // ANSWERS ARRAY AND SHUFFLE
  let answers = [...question.incorrect_answers, question.correct_answer];
  shuffle(answers);

  return (
    <Question
      key={index}
      index={index}
      question={question.question}
      answers={answers}
      setAnswer={setAnswer}
    />
  );
});

如果我没记错的话,我知道您想更新父组件的 state。 您可以将 setState function 作为道具传递给子组件,如下所示:

 return ( <Question key={index} index={index} question={question.question} answers={answers} updateScore ={setScore}/> )

  1. 您可以使用相同的道具并通过 setScore 挂钩来设置值。
  2. 您可以使用Redux并从中获取/设置值。

大多数人更喜欢 redux 而不是将 setState 钩子作为道具传递给孩子,但是很多时候人们将钩子作为道具传递并解决了这个问题。

希望这对你有帮助!

暂无
暂无

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

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