reactjs - 通过 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'
解决方案
推荐阅读
- sql - LEFT JOIN 正在杀死我的查询 - 如何加快速度?
- ruby-on-rails - Rails - 如何向 Fastjson api 添加分页?
- amazon-web-services - 使用 Terraform 更改 hash_key 会导致表已存在错误
- c# - 相机不与播放器一起旋转 360 度视频录制中的播放器统一
- azure-cosmosdb - 即使 maxItemCount 设置为 -1,Cosmos Db 也不会返回所有记录
- javascript - 无法制作四种不同颜色的轮子
- office-js - Excel 加载项 | 根据条件启用/禁用功能区图标
- python - 如何在 FastApi 中隐藏输入参数?
- mongodb - Mongodb查询以检索月份范围内的数据
- python - 条件语句快捷方式(python)