我有一个功能,试图获取一系列电子邮件并检查其是否为有效电子邮件:
handleValidEmail = (isValid, index, emailValue) => {
// checks if empty state in optional fields.
const { emailValueList, isValidEmailArray, isValidEmail } = this.state;
// need to make copy, to treat the array as immutable
const newEmailValueList = [...emailValueList];
newEmailValueList[index] = emailValue;
const newIsValidEmailArray = [...isValidEmailArray];
newIsValidEmailArray[index] = isValid;
this.setState({
emailValueList: newEmailValueList,
isValidEmailArray: newIsValidEmailArray,
}, () => {
console.log(emailValueList, isValidEmailArray);
console.log('before', isValidEmail);
if (every(isValidEmailArray, Boolean)) {
this.setState({ isValidEmail: isValid });
} else {
this.setState({ isValidEmail: false });
}
console.log('isvalidEmail', isValidEmail);
});
}
因此,我做了一些挖掘工作,并且我知道如果您对setState进行回调,它应该可以工作。但是,我不是要上班。
因此,当我在输入字段“ test@gmail.co”中键入内容时,控制台将记录:
console.log(emailValueList, isValidEmailArray);
= ["test@gmail.c"], [false]
console.log('before', isValidEmail);
= before false
console.log('isvalidEmail', isValidEmail);
= isvalidEmail false
当我输入最后一个字母“ m”以使其为test@gmail.com
console.log(emailValueList, isValidEmailArray);
= ["test@gmail.co"], [true]
console.log('before', isValidEmail);
= before false
console.log('isvalidEmail', isValidEmail);
= isvalidEmail false
然后,当我在末尾添加另一个字母时:
console.log(emailValueList, isValidEmailArray);
= ["test@gmail.com"], [true]
console.log('before', isValidEmail);
= before true
console.log('isvalidEmail', isValidEmail);
= isvalidEmail true
我试图让isValidEmail在testing@gmail.co
上遇到第一个true时为true
为什么我没有得到这个结果?
答案 0 :(得分:1)
尝试更改此 if (every(isValidEmailArray, Boolean)) {
对此: if (every(newIsValidEmailArray, Boolean)) {
您仍在引用旧状态。
除非您将其放在setState
:console.log('isvalidEmail', isValidEmail);
对setState的调用不是“即时”的: https://reactjs.org/docs/react-component.html#setstate