函数仅检查数组中的最后一项

时间:2018-10-09 09:59:34

标签: javascript reactjs

我有一个功能,可以验证用户提交的电子邮件。我通过将用户电子邮件与每个有效的电子邮件域进行比较来做到这一点。我将用户提交的电子邮件存储在数组中,并将有效的电子邮件域也存储在数组中。问题在于使用该函数时,它仅检查用户数组中的最后一个值是否有效,而不检查它之前的元素。

我的功能:

handelTeamError = () => {
    var array = []; //user emails get put in here 
    var emailcheck = EmailDomeinen(); //array with valid email domains
    const emailrow = this.state.rows.map(x => array.push(x.email)); //every email that user submitted

    //if user submitted nothing function will return false; user can't continue
    if(!emailrow){
        this.setState(() => ({tlemailError: true}));
        return false;
    }else{
        for(let i = 0; i < emailcheck.length; i++){
            let email = emailcheck[i]; //get all the valid emails
            for(let j = 0; j < array.length; j++){
                let res = array[j].split("@", 1).toString(); //checks if user typed more than only the email domain
                if(!array[j].endsWith("@" + email)){ //if the user value ends with @ and a valid email domains
                    this.state.rows.map( x => x.tlEmailError = true); //error state = true
                }else{
                    if(res){
                        this.state.rows.map( x => x.tlEmailError = false); //error state = false
                        return true; // user can continue 
                    }
                }
            }
        }
        return false;
    }
};

2 个答案:

答案 0 :(得分:1)

我发现您的方法存在一些问题。

首先emailrow看起来将永远是一个数组(为空或已填充),因此if(!emailrow){将始终返回false。您应该使用if(!emailrow.length){

然后,您的算法似乎正在检查每个用户电子邮件是否以 all 结尾的有效域,这是可以理解的。您的外部循环应该是用户电子邮件,内部循环应该尝试查找有效域之一是否与之匹配。

最后,您似乎正在尝试直接修改this.state.rows内部的状态,而不是使用setState函数,这是正确的方法。

因此,重构版本可能是

// this assumes that you have a sigle tlEmailError property in your state 
// and not one for each email
handelTeamError = () => {
  const validDomains = EmailDomeinen(); //array with valid email domains
  const userEmails = this.state.rows.map(row => row.email); //every email that user submitted

  // check if all emails are valid
  const allValid = userEmails.every(email => {
    const isValid = email.indexOf('@') > 0,
      userDomain = email.split('@')[1];

    return (isValid && validDomains.some(domain => domain === userDomain));
  });

  const result = userEmails.length && allValid;

  this.setState({
    tlEmailError: result
  });

  return result;
}

答案 1 :(得分:0)

此外:由于您使用map,因此可以使用另外两种JS数组方法来减少代码占用:reduceincludes

const state = [{ name: 'bob', email: 'bob@gmail.com'}, { name: 'dan', email: 'dan@yahoo.com'},{ name: 'tree', email: 'tree@tree.com'},{ name: 'pete', email: 'pete@aol.com'}];
const emailCheck = ['aol.com', 'gmail.com'];

const array = state.reduce((arr, cur) => {
  const domain = cur.email.split('@')[1];
  emailCheck.includes(domain) ? cur.emailError = true : cur.emailError = false;
  return arr.concat(cur);
}, []);

console.log(array);