[英]React state not available after using setState
I'm working on a trivia app using ReactjS and every time I try to update my state named "game", I get the following error message:我正在使用 ReactjS 开发一个琐事应用程序,每次尝试更新名为“游戏”的 state 时,都会收到以下错误消息:
Uncaught TypeError: game is undefined.
My webapp is structured as follows: App -> Question -> Answers.我的 webapp 的结构如下:App -> Question -> Answers。
in App:在应用程序中:
const [game, setGame] = React.useState([]);
function holdAnswer(qKey) {
console.log(qKey);
setGame((oldGame) => {
oldGame.map((element) => {
return qKey === element.key ? {} : element;
});
});
console.log(qKey);
}
React.useEffect(function () {
console.log("Effect ran");
fetch("https://opentdb.com/api.php?amount=5")
.then((res) => res.json())
.then((data) =>
setGame(
data.results.map(function (element) {
return {
...element,
key: uniqid(),
answers: arrayShuffle([
...element.incorrect_answers.map(
(x) => new AnswerObj(x, false, uniqid())
),
new AnswerObj(element.correct_answer, false, uniqid()),
]),
};
})
)
);
console.log(game);
}, []);
var wholeQ = game.map((element) => {
return (
<Question wQ={element} holdAnswer={() => holdAnswer(element.key)} />
);
});
in Question Component:在问题组件中:
export default function Question(props) {
const answers = arrayShuffle(props.wQ.answers).map((element) => {
return <Answers wholeAnswer={element} holdAnswer={props.holdAnswer} />;
});
return (
<div className="question">
<p>{decode(props.wQ.question)}</p>
<div className="answer-buttons-wrapper">{answers}</div>
</div>
);
}
in Answers Component:在答案组件中:
export default function Answers(props) {
return (
<button className="answer-button" onClick={props.holdAnswer}>
{decode(props.wholeAnswer.answer)}
</button>
);
}
I believe the problem lies in the following block:我相信问题出在以下块:
function holdAnswer(qKey) {
console.log(qKey);
setGame((oldGame) => {
oldGame.map((element) => {
return qKey === element.key ? {} : element;
});
});
console.log(qKey);
}
As setGame
ends up not returning anything and therefor sets the state with an undefined
value.由于
setGame
最终没有返回任何内容,因此将 state 设置为undefined
的值。
To address this we can remove the curly-braces in setGame
in-order to make it an "implicit return" .为了解决这个问题,我们可以删除
setGame
中的花括号以使其成为“隐式返回” 。
Alternatively, we can add a return statement before the mapping function.或者,我们可以在映射 function 之前添加一个返回语句。
// Either this ->
setGame((oldGame) =>
oldGame.map((element) => {
return qKey === element.key ? {} : element;
});
);
// Or this ->
setGame((oldGame) => {
return oldGame.map((element) => {
return qKey === element.key ? {} : element;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.