axios请求then回调中useRef不生效,无法创建动态OTP输入框引用
OTP动态输入框useRef调用异常修复方案
问题根因
React Hooks有强制调用规则,useRef仅允许在函数组件的顶层作用域调用,禁止在异步回调、循环、条件分支等非顶层代码中执行。你在axios请求的then回调内调用useRef,直接触发Hook规则校验报错,代码执行中断,所以后续的console.log("inputRef",inputRef)没有运行。
修复方案
不需要动态生成多个useRef实例,用单个ref存储输入框引用数组即可,实现步骤如下:
- 在组件顶层声明对应变量
import { useRef, useState } from 'react' // 存储所有OTP输入框的DOM引用 const otpInputRefs = useRef<(HTMLInputElement | null)[]>([]) // 状态存储OTP验证码位数,初始为0 const [otpDigits, setOtpDigits] = useState(0)
- 修改请求回调逻辑,删除动态生成useRef的代码,仅更新OTP位数状态
api.post('auth/login', { mobile:_mobile}).then((res: any) => { // 清空之前的引用缓存 otpInputRefs.current = [] // 更新OTP位数 setOtpDigits(res.digits) const now = new Date(); now.setMinutes(now.getMinutes() + ( parseInt(res.expired_at)/60)); setExpiredAt(now.getTime()) showLoading(false); toggleVerification(true); }).catch(() => { showLoading(false) })
- 渲染OTP输入框时通过回调ref存入引用数组
{Array.from({ length: otpDigits }).map((_, index) => ( <input key={index} ref={(el) => otpInputRefs.current[index] = el} type="text" maxLength={1} // 其他输入框属性、事件绑定 /> ))}
- 操作输入框时直接访问对应索引的引用即可,例如下标移动、自动聚焦逻辑:
const handleInput = (index: number, inputValue: string) => { // 输入完成后自动聚焦下一个输入框 if (inputValue.trim() && index < otpDigits - 1) { otpInputRefs.current[index + 1]?.focus() } }
内容的提问来源于stack exchange,提问作者S.M_Emamian
相关产品推荐
相关产品推荐

