【发布时间】:2021-12-24 18:41:46
【问题描述】:
我正在获取一个名为 Quiz 的对象。我试图将 Quiz (questionAnswerPair) 的单个元素传递给名为 QuestionAnswer 的子元素。
测验收集得很好,每个元素都可以迭代。然而,尽管这不是我发帖的原因,但目前集成并没有按预期工作。
我发帖的原因是 QuestionAnswerPair 没有正确传递给子元素(在子组件中打印时显示未定义)。
父母:
export default function Quiz() {
var passedid = 1; //need to replace this with passed quiz ID
const [quiz, setQuiz ]=useState('')
const [executedFetch, setExecutedFetch]=useState('')
useEffect(() => {
fetch(`http://XXX.XXX.XXX.XXX:8080/Quiz/${passedid}`)
.then(response => response.json())
.then(json => {
console.log(json)
setQuiz(json)
setExecutedFetch(true)
})
},[])
const [currentQuestionAnswerPair, setCurrentQuestionAnswerPair]=useState('')
const [executedIterate, setExecutedIterate]=useState('')
//this runs twice, once before the data collection and
//one after which is why it needs the conditional if
useEffect(() => {
if (executedFetch === true){
for (var i=0; i < quiz.questionAnswerPairs?.length; i++ )
{
console.log(quiz.questionAnswerPairs[i]) //prints current fine
setCurrentQuestionAnswerPair(quiz.questionAnswerPairs[i])
setExecutedIterate(true)
// make it wait till the question is answered somehow
// then store the answer within an attempt
}
//set entire attempt here
}
},[executedFetch])
const[ userSelectionData, setUserSelectionData]=useState('')
const childToParent = (userSelectionData) => {
setUserSelectionData(userSelectionData);
}
const parentToChild = () => {
setParentToChildData(currentQuestionAnswerPair);
}
if (executedIterate === true){
console.log("executedIterate " + executedIterate)
console.log(currentQuestionAnswerPair)
return (
<br/> <br/> <br/> <br/>
parent data = {userSelectionData}
<br/> <br/> <br/> <br/>
<QuestionAnswer parentToChild={currentQuestionAnswerPair} childToParent={childToParent}/>
</div>
);
}
else{
return (
<div className="App">
not displaying
</div>
);
}
}
孩子:
export default function QuestionAnswer({currentQuestionAnswerPair,childToParent}) {
const userSelectionData = "child data passed"
const [questionAnswer, setQuestionAnswer]=useState('')
useEffect(() => {
console.log(currentQuestionAnswerPair) // this is undefined
setQuestionAnswer(currentQuestionAnswerPair)
},[])
console.log(currentQuestionAnswerPair) // this is undefined
console.log(questionAnswer) // this is undefined
return (
<div>
<br/>
current question answer = {questionAnswer}
<br/> <br/>
current question answer pair = {currentQuestionAnswerPair}
<br/> <br/>
<Button primary onClick={() => childToParent(userSelectionData)}>Click Child</Button>
</div>
)
}
此外,将依赖项传递给子 useEffect [currentQuestionAnswerPair] 不会改变问题
【问题讨论】:
-
您将
currentQuestionAnswerPair变量传递给 childToParent 道具,因此当您尝试检索它时,您正在寻找您从未定义过的道具
标签: javascript reactjs json react-hooks