[英]Error when calling a function from the child to change the state of the parent
我试图通过单击子组件中的按钮将父级的 state 更改为某些内容。 问题是,当我单击按钮时,我收到错误警告:无法在呈现不同组件( Quiz
)时更新组件( App
)。 在Quiz
中找到错误的 setState() 调用
我的 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;
我的测验.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
问题在这里
<button onClick={props.finalAnswer(props.choice1)}>{props.choice1}</button>...
.
您实际上并没有分配 function,您正在调用 function finalAnswer(choice)
并且它正在尝试更改父级(App)
rending
,同时正在渲染,这就是您看到该警告的原因。
您只需要将finalAnswer
包装在回调中。
像这样尝试
<button onClick={() => props.finalAnswer(props.choice1) }>{props.choice1}</button>
... and all for others.
注意:有更好的方法来做你的事情,尝试找到简单的解决方案而不是单独处理state
。
这里有一个类似的问题,您可以找到简单的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.