useState() Hook未按预期工作?输入赋值错误且signIn弹窗为空如何解决
问题原因
setInput函数未接收输入框传递的输入值,内部更新状态时直接用旧状态值重新赋值,导致输入内容没有正确同步到state中- 按钮点击事件使用了小写
onclick,不符合React事件驼峰命名规范,绑定的回调函数不会被触发 step1、step2定义在state声明之前,内部回调形成闭包引用的始终是初始化时的空状态值,就算触发回调也拿不到最新的输入内容- 步骤切换、提交的回调中存在无意义的
setEmail(email)、setPassword(password)逻辑,既没有更新值的作用,还可能引发不必要的重渲染
解决方案
- 修正
setInput逻辑,接收输入值作为参数,根据当前步骤更新对应的email或password状态 - 将按钮的
onclick修改为React规范的驼峰写法onClick - 调整状态存储逻辑,改用数字存储当前步骤编号,避免把带回调的对象存入state引发闭包问题
- 移除回调中无意义的重复赋值逻辑
修正后完整代码
import React, { useState } from "react" const Auth = () => { const [currentStep, setCurrentStep] = useState(1) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const signIn = () => { alert(email + password) } const stepConfig = { 1: { stepCount: "Step 01/02", title: "Enter email", helperText: "Enter your email to sign in to your account. Or if you don't have an account no worries! .We will create an account for ya !", inputType: "email", btnText: "Next", onBtnClick: () => setCurrentStep(2) }, 2: { stepCount: "Step 02/02", title: "Enter password", helperText: "If you have an account, enter your set password or if you dont't have an account enter a strong password for your acccount.", inputType: "password", btnText: "Proceed", onBtnClick: signIn } } const currentStepInfo = stepConfig[currentStep] const setInput = (value) => { currentStep === 1 ? setEmail(value) : setPassword(value) } return ( <div style={{ display: "flex", flexFlow: "column", alignItems: "center", }}> <h4 style={{ marginTop: "20px", marginBottom: "10px", color: "#a3a3a3", }}> {currentStepInfo.stepCount} </h4> <h2 style={{ marginBottom: "35px" }}> {currentStepInfo.title} </h2> <h4 style={{ marginBottom: "50px", color: "#b2b2b2", fontWeight: "500", }}> {currentStepInfo.helperText} </h4> <input type={currentStepInfo.inputType} onChange={e => setInput(e.target.value)} style={{marginBottom: "35px"}} /> <button onClick={currentStepInfo.onBtnClick}>{currentStepInfo.btnText}</button> </div> ) } export default Auth
内容的提问来源于stack exchange,提问作者Ron Bis
相关产品推荐
相关产品推荐

