I continue to get the following error
Objects are not valid as a React child (found: object with keys {questionId, answer}). If you meant to render a collection of children, use an array instead.
I realise it is quite a common error on here but I can't seem to figure it out. Any help or pointers in the right direction would be great.
const [currentQuestion, setCurrentQuestion] = useState(0)
const [selectedAnswer, setAnswer] = useState('')
const [savedAnswers, setSavedAnswers] = useState([])
const question = questions[currentQuestion]
const handleNextQuestion = () => {
if(currentQuestion < questions.length - 1) {
//create answer array item
const answer = {questionId: question, answer: selectedAnswer};
//add saved answer to array
setSavedAnswers(savedAnswers => [...savedAnswers, answer])
//go to next question
setCurrentQuestion(currentQuestion + 1)
//clear next answer
setAnswer('')
}
}
return (
<div className="section">
<div className="container">
<div className={styles.surveyContainer}>
<h2 className="title is-2 has-text-centered">Feel</h2>
<Progress
total = {questions.length}
current = {currentQuestion + 1}
/>
<Question
question = {question.question}
/>
<Answers
answers = {question}
selected = {selectedAnswer}
handleClick = {handleClick}
/>
</div>
<button className="button is-primary" onClick={handleNextQuestion}>Next</button>
{selectedAnswer}Selected Answers
{savedAnswers}Saved Answers
</div>
</div>
)
You need to map the array of answers. Use the questionId
for the react key.
savedAnswers.map(({ questionId, answer }) => (
<div key={questionId}>{answer}</div>
));
当您让 React 渲染对象而不是普通元素时,通常会发生此错误。
const [currentQuestion, setCurrentQuestion] = useState(0]) 也定义这个
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.