【发布时间】:2020-09-11 23:23:15
【问题描述】:
我在 Next.js 应用程序中使用 Formik,但我遇到了一个不知道如何解决的问题。我的提交 Button 是一个接受 showSpinner 道具的组件。如果为 true -> 按钮被禁用,并且显示按钮中的加载微调器。 showSpinner 值取决于来自 useState 钩子的 loading。以下是相关代码:
export default function register() {
const [loading, setLoading] = useState(false)
return (
<>
<Layout>
<div className={styles.registerContainer}>
<div className={styles.registerFormContainer}>
<h1 className={styles.registerHeader}>Sign Up</h1>
<Formik
initialValues={{
email: '',
password: '',
passwordConfirm: '',
acceptedTerms: false
}}
onSubmit={
(values, { setSubmitting }) => {
console.log(loading)
// here loading == false as expected
setLoading(true)
console.log(loading)
// here loading == false even though i set it to true
initFirebase()
firebase.auth().createUserWithEmailAndPassword(values.email, values.password)
.then((res) => {
console.log('done!')
})
.catch(function (error) {
// Handle Errors here.
console.log(error)
})
.finally(() => {
console.log(loading)
//here loading == false too, even though I expected it to be true
setSubmitting(false)
setLoading(false)
})
}
}
>
<Form>
<FormikText label="Email:"
name="email"
type="email"
id="email" />
<FormikPassword label="Password:"
name="password"
id="password"
/>
<FormikPassword label="Confirm Password:"
name="passwordConfirm"
id="passwordCOnfirm"
/>
<FormikCheckbox
name="acceptedTerms"
id="acceptedTerms"
>
<span className={styles.checkboxLabel}>
I agree to the <Link href="/terms" ><a className={styles.registerLink}>Terms of Service</a></Link> and <Link href="/privacy"><a className={styles.registerLink}>Privacy/Cookie Policy</a></Link>
</span>
</FormikCheckbox>
<div className={styles.buttonContainer}>
<Button type="submit" color="blue" showSpinner={loading}>Sign Up</Button>
</div>
</Form>
</Formik>
</div>
</div>
</Layout>
</>
)
}
即使我的Button 以某种方式按预期工作(微调器按预期显示),在通过loading 的console.loging 值通过onSubmit 函数调用之后,我注意到它是false,我期望它会这样做是真的。是因为 React 批处理 useState 调用的方式吗?
我的问题是:
- 如何正确处理这种情况?
- 如果
loading == false在那些console.logs中,为什么我的Button按预期工作?
【问题讨论】:
-
我首先检查一下 setLoading() 在 onSubmit 函数中的计算结果。您可以定义一个虚拟函数并查看它是否在 onSubmit 中正确触发。
标签: javascript reactjs next.js formik