基于计时器类,警告:无法在现有状态转换期间进行更新(例如在"render"中)



我试着阅读过这个问题的类似解决方案,但都无法解决我的问题。从控制台错误来看,它表明我在这一行中有一个错误

this.setState({ submitted: true, finalScore });

我目前正在使用ReactJS制作一个有计时器的问答应用程序。一旦计时器达到0,它将自动提交答案。

这是我的渲染

render() {
const { questionBank, submitted, finalScore, minute, second } = this.state;

return (
<Box>
<h2>Pop Quiz!</h2>
<h3>Time remaining: {minute}:{second< 10 ? `0${ second }` : second}</h3>
{ minute === 0 && second === 0
? this.handleSubmit() : <div>{!submitted &&
questionBank.length > 0 &&
questionBank.map(
({ question, answers, correct, questionId }, index) => (
<QuestionBox
key={questionId}
index={index + 1}
question={question}
options={answers}
selected={(answer) =>
this.computeAnswer(answer, correct, questionId)
}
/>
)
)}
{!submitted && (
<Box align="end">
<Button
primary
label="Submit"
onClick={() => this.handleSubmit()}
/>
</Box>
)}
{submitted && <Result score={finalScore} playAgain={this.playAgain} />}
</div>
}
</Box>
);
}

这是我的计时器

timer = () => {
this.myInterval = setInterval(() => {
const { second, minute } = this.state
if (second > 0) {
this.setState(({ second }) => ({
second: second - 1
}))
}
if (second === 0) {
if (minute === 0) {
clearInterval(this.myInterval)
} else {
this.setState(({ minute }) => ({
minute: minute - 1,
second: 59
}))
}
}
}, 1000)
}
componentDidMount() {
this.getQuestions();
this.timer();
}

这是handleSubmit

handleSubmit() {
const {
correctQuestionAnswered,
questionBank: { length },
} = this.state;
const { db } = this.props;
const finalScore = ((correctQuestionAnswered / length) * 100).toFixed(2);
const currentdate = new Date();
const dateTime =
currentdate.getDate() +
"/" +
(currentdate.getMonth() + 1) +
"/" +
currentdate.getFullYear() +
" @ " +
currentdate.getHours() +
":" +
currentdate.getMinutes() +
":" +
currentdate.getSeconds();
db.put({
_id: new Date().toJSON(),
submit_datetime: dateTime,
score: finalScore,
});
this.setState({ submitted: true, finalScore }); // <--- This is the line that I get an error
this.forceUpdate();
}

我哪里出了问题,导致了这样的结果?我对reactJS 还是个新手

Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state

//编辑:在进行了更多调整后,我设法在00:00时将submitHandler移动到计时器,并擦除submitHandler中的this.forceUpdate(),从而解决了问题。然而,我仍然不完全确定为什么以前的设计不起作用。

Simple,您在render方法中调用setState,这在React中是不允许的。

render方法中的这行代码非法导致调用setState:

{ minute === 0 && second === 0
? this.handleSubmit()

您应该将此状态检查移动到组件类中的componentDidUpdate()方法中。简而言之,只要组件的道具或状态发生变化(换句话说,只要组件渲染(,就会调用componentDidUpdate()。点击此处了解componentDidUpdate((

在这里,您应该检查minutesecond的状态,并相应地调用handleSubmit((方法:

componentDidUpdate() {
if(this.state.minute === 0 && this.state.second === 0) {
this.handleSubmit()
}
}

并从渲染方法中删除minute === 0 && second === 0三进制。

如果您在实施我的解决方案时有任何问题,请在评论中告诉我。

自从你解决了这个问题后,我没有详细介绍你的代码,但我相信这是因为你在render((方法中调用了你的状态。每次发生变化(对你来说,因为你一直在倒计时(,你的状态都会陷入无限循环。它应该在constructor((中提及,或者使用redux之类的工具。

编辑:打到拳,更优雅。。。

最新更新