【问题标题】:React-Phone-Number-Input + React-Hook-Form: How to get current country code in controller validation?React-Phone-Number-Input + React-Hook-Form:如何在控制器验证中获取当前国家代码?
【发布时间】:2022-07-10 00:03:23
【问题描述】:

我正在使用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"
    />
  )}
/>

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

    这是一个特定的反应,图书馆没有错。 React 从不立即更新状态 react 中的状态更新是异步的;当那里请求更新时;不保证会立即进行更新。然后 updater 函数将组件状态的更改排入队列,但 react 可能会延迟更改。

    例如:

    const [age, setAge] = useSate(21);
    const handleClick = () => {
        setAge(24)
        console.log("Age:", age);
    }
    

    您将在控制台中看到 21 人登录

    这就是 react 的工作原理。在您的情况下,当您更改国家/地区时,此“onCountryChange”事件会触发更新功能以更新状态并验证电话号码,但状态尚未更新,这就是它选择以前的 countryCode 值的原因(在此处进行控制台日志)。

    为了更清楚地理解这一点,请将这段代码放入您的组件中。

    useEffect(() => {
        console.log("useEffect: phoneCountryCode", phoneCountryCode);
      }, [phoneCountryCode]);
    
    
    console.log(phoneCountryCode, value); // inside isValid()
    

    useEffect 回调将在 phoneCountryCode 值更新时调用,并且在状态更新之前调用 isValid() 中的 console.log。

    希望这是有道理的。快乐编码!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 1970-01-01
      • 2023-01-31
      • 2021-12-09
      • 2020-04-11
      • 1970-01-01
      相关资源
      最近更新 更多