簡體   English   中英

React-Phone-Number-Input + React-Hook-Form:如何在控制器驗證中獲取當前國家代碼?

[英]React-Phone-Number-Input + React-Hook-Form: How to get current country code in controller validation?

我正在使用react-phone-number-input庫。 不需要輸入電話號碼,但如果該號碼存在,我希望在發送表單之前對其進行驗證。

如果提交表單時cellphone字段是原始的/未觸及,則isValid接受undefined (有效狀態)。

如果國家代碼立即更改(沒有實際輸入號碼), isValid接受所選國家的呼叫代碼(例如瑞典的+46 )。 這仍然是一個完全有效的案例。

isValid函數中訪問時, phoneCountryCode始終保存先前選擇的值。 因此,經過驗證的電話號碼和當前的國家代碼之間總是存在差異。 我不確定問題是否是特定於庫的,也許是我的錯誤。 我如何擺脫提到的差異?

在 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 中的狀態更新是異步的; 當請求更新時,不能保證會立即進行更新。 然后更新函數將更改加入到組件狀態,但反應可能會延遲更改。

例如:

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()

更新 phoneCountryCode 值時將調用 useEffect 回調,並且將在狀態更新之前調用 isValid() 中的 console.log。

希望這是有道理的。 編碼快樂!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM