我正在使用react-phone-number-input图书馆。不需要输入电话号码,但如果存在该号码,我希望可以在发送表格之前对其进行验证。
如果提交表单时cellphone
字段是原始的/未受影响,则isValid
接受undefined
(有效状态)。
如果立即更改国家/地区代码(无需实际输入号码)isValid
接受所选国家/地区的调用代码(例如瑞典的 +46)。这仍然是一个完全有效的案例。
在 isValid
函数中访问时,phoneCountryCode
始终保留先前选择的值。因此,经过验证的电话号码与当前国家/地区代码之间始终存在差异。我不确定问题是否是特定于库的,也许这是我的错误。如何消除上述差异?
我做了一个reproduction on CodeSandbox .
import PhoneInput, {
parsePhoneNumber,
getCountryCallingCode
} from "react-phone-number-input";
const [phoneCountryCode, phoneCountryCodeSetter] = useState('DE');
<Controller
name="cellphone"
rules={{
validate: {
isValid: value => {
if(value) {
const callingCode = getCountryCallingCode(phoneCountryCode);
if(! new RegExp(`^\\+${callingCode}$`).test(value)) {
// The parsePhoneNumber utility returns null
// if provided with only the calling code
return !!parsePhoneNumber(value);
}
}
return true;
}
}
}}
control={control}
render={({ field }) => (
<PhoneInput
{...field}
onCountryChange={(v) => phoneCountryCodeSetter(v)}
limitMaxLength={true}
international={true}
defaultCountry="DE"
/>
)}
/>
最佳答案
这是特定于 react 的,库中没有任何错误。 React 永远不会立即更新状态,React 中的状态更新是异步的;当请求更新时,不能保证立即进行更新。然后更新函数将更改排队到组件状态,但 react 可能会延迟更改。
例如:
const [age, setAge] = useSate(21);
const handleClick = () => {
setAge(24)
console.log("Age:", age);
}
您将在控制台中看到 21 条记录。
这就是 React 的工作原理。在您的情况下,当您更改国家/地区时,此“onCountryChange”事件会触发更新功能来更新状态并验证电话号码,但状态尚未更新,这就是它选择以前的国家/地区代码值的原因(在此处进行控制台登录)。
为了更清楚地理解这一点,请将此代码放入您的组件中。
useEffect(() => {
console.log("useEffect: phoneCountryCode", phoneCountryCode);
}, [phoneCountryCode]);
console.log(phoneCountryCode, value); // inside isValid()
当phoneCountryCode值更新时,将调用useEffect回调,并且在状态更新之前,将调用isValid()内的console.log。
希望这是有道理的。快乐编码!!
关于reactjs - React-电话号码-输入 + React-Hook-Form : How to get current country code in controller validation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71873553/