I am attempting to change the state of the parent to something upon a button click in the child component. The issue is that when I click the button I get the error Warning: Cannot update a component (App
) while rendering a different component (Quiz
). To locate the bad setState() call inside Quiz
- Essentially, what I am trying to do is have a couple of buttons with statements on them. When a button is clicked the statement that is on the button is passed to the parent state, which in this case is the choices[1-4] and answers[1-4].
My App.js
import React, { useState } from 'react';
import './App.css';
//import components
import Quiz from './components/Quiz'
function App() {
//states
const [question, setQuestion] = useState("Ready to start?");
//what question we are on
const [counter, setCounter] = useState(0);
//buttons that display the available answers to choose from
const [choice1, setchoice1] = useState("choice1");
const [choice2, setchoice2] = useState("choice2");
const [choice3, setchoice3] = useState("choice3");
const [choice4, setchoice4] = useState("choice4");
// final answer for each question
const [answer1, setAnswer1] = useState("")
const [answer2, setAnswer2] = useState("")
const [answer3, setAnswer3] = useState("")
const [answer4, setAnswer4] = useState("")
const nextQuestion = () => {
if (counter === 0) {
setQuestion((prev) => "question 1")
} else if (counter === 1) {
setQuestion((prev) => "question 2")
} else if (counter === 2) {
setQuestion((prev) => "question 3")
} else if (counter === 3) {
setQuestion((prev) => "question 4")
} else if (counter === 4) {
setQuestion((prev) => "question 5")
} else {
setQuestion((prev) => "complete")
}
}
const finalAnswer = (param) => {
if (counter === 1) {
setAnswer1(param);
} else if (counter === 2) {
setAnswer2(param);
} else if (counter === 3) {
setAnswer3(param);
} else if (counter === 4) {
setAnswer4(param);
}
}
const incrementer = () => {
setCounter((prev) => prev + 1);
console.log(counter);
nextQuestion();
}
return (
<div className="App">
<Quiz question={question} counter={incrementer}
nextQuestion={nextQuestion} choice1={choice1}
choice2={choice2} choice3={choice3} choice4={choice4} finalAnswer={finalAnswer} />
</div>
);
}
export default App;
My Quiz.js
import React from 'react';
const Quiz = (props) => {
return (
<div>
<h1>
{props.question}
</h1>
<button onClick={props.finalAnswer(props.choice1)}>{props.choice1}</button>
<button onClick={props.finalAnswer(props.choice2)}>{props.choice2}</button>
<button onClick={props.finalAnswer(props.choice3)}>{props.choice3}</button>
<button onClick={props.finalAnswer(props.choice4)}>{props.choice4}</button>
<button onClick={props.counter}>next</button>
</div>
)
}
export default Quiz
Aucun commentaire:
Enregistrer un commentaire