gpt4 book ai didi

javascript - 在 React.js 上验证电话号码

转载 作者:行者123 更新时间:2023-11-30 19:01:16 24 4
gpt4 key购买 nike

我正在尝试验证电话字段,以使用下面的代码获取所有字母和点。

validatePhone = () => {
const sanitizedPhone = this.state.phone.replace(/\D/g, '');
if (sanitizedPhone.length >= 10 && sanitizedPhone.length <= 11) {
this.setState({ phone: sanitizedPhone });
return true;
}
toast.error('Invalid phoneNumber.', {
position: "top-center",
autoClose: false,
closeOnClick: true,
});
return false;
}

当我尝试在 console.log(sanitizedPhone) 中输入点时,如 11.97.4.4.51234 我得到 11974451234 但在此之后,在 console.log(this.state.phone) 上,我得到了旧号码 11.97.4.4.51234

最佳答案

来自 react docs :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

这就是为什么在使用 setState 后看不到更改的原因。

关于javascript - 在 React.js 上验证电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com