首页 > 解决方案 > 通过 refs 访问 phone-react-input-2 组件时,我没有得到更新的状态

问题描述

我想编辑还包含电话号码的用户详细信息。该电话号码还包括国家代码。我正在使用 react-phone-input-2 组件,它的值是我要编辑的用户的电话号码。当在此 phoneInput 组件上调用 onChange 时,它​​接受国家代码和电话号码作为参数,并且在该 onChange 回调函数中,我将电话号码和国家代码分开。现在,如果我不编辑电话号码字段而是其他一些字段,则不会调用电话号码的 onChange,因为它没有被编辑,电话号码和国家代码将不会分开。我想以某种方式将国家代码与电话号码分开。所以我使用 ref 访问 dom 节点并获取它的当前状态,因为在 state 内部的 selectedCountries 对象中存在国家代码和电话号码。当我 console.log (在 useEffect 块中)那个phoneRef。当前它给了我正确的值,而如果我使用 phoneRef.current.state 访问状态,它给了我错误的值。我不明白为什么。

           /*react-phone-input-2 component*/
              <PhoneInput
                country={"nl"}
                inputClass={"phone-input-class"}
                constainerClass={"phone-input-class"}
                ref={phoneRef}
                inputStyle={{
                  color: "white",
                  boxShadow: "none",
                  border: "1px solid transparent",
                  borderRadius: 8,
                  backgroundColor: PURE_BLACK,
                  fontSize: 12,
                  padding: "20px 0px 20px 58px",
                }}
                containerStyle={{ marginTop: 5 }}
                buttonStyle={{}}
                value={players[ind].phoneNumber}
                onChange={(phoneOnly = "", code = "") => {

                  // manageState(phoneOnly, ind, 'phoneNumber')
                  phoneOnly = `${phoneOnly.replace(code.dialCode, "")}`
                  manageCode(phoneOnly, code.dialCode, ind)
                }}
              />
        /*accessing state and calling managecode which separates country code and phone 
         num and set local state of component*/
           useEffect(() => {
               if (!edit)
                 localStorage.setItem("add_players_state", JSON.stringify(players));
               if (edit && !checkKeyInObject(...players, 'country_code', 'bool', false)) {
                  **console.log(phoneRef.current, phoneRef.current.state)**
                   checkKeyInObject(...players, 'phoneNumber', 'value', '') != "" && 
                       manageCode(editPlayer.phoneNumber, 
                       phoneRef.current.state.selectedCountry.dialCode, 0)
                  }
             }, [players]);

console.log(phoneRef.current) 的输出:

{
.....
state:{
 selectedCounty:{
                 ....
               dialCode:'92'
                }
  }    
}
Output of console.log(phoneRef.current.state):
    {
     .....
        selectedCounty:{
               .....
               dialCode:'31'
                }
     } 
}

这个 dialCode 31 是默认的,因为国家在 phoneInput 中默认设置为 'nl'

标签: reactjsstateref

解决方案


推荐阅读