0

我不明白这部分代码:

this.setState({ usernameValid, errorMsg }, this.validateForm);

如果我们正在更新usernameValid,errorMsg状态,会this.validateForm做什么?因为我们是在setState.

我的代码:

class StandardForm extends Component {
      state = {
        username: "",
        usernameValid: false,
        email: "",
        emailValid: false,
        password: "",
        passwordValid: false,
        passwordConfirm: "",
        passwordConfirmValid: false,
        formValid: false,
        errorMsg: {},
      };

  validateForm = () =>{
    let { usernameValid, emailValid, passwordValid, passwordConfirmValid} = this.state;
    this.setState({
      formValid: usernameValid && emailValid && passwordValid && passwordConfirmValid
    })
  }

  validateUsername = () => {
    const { username } = this.state;
    let usernameValid = true;
    let errorMsg = { ...this.state.errorMsg };

    if (username.length < 6 || username.length > 16) {
      usernameValid = false;
      errorMsg.username = "Username should be between 6 and 15 characters";
    }
    this.setState({ usernameValid, errorMsg }, this.validateForm);
  };

  validateEmail = () => {
    const { email } = this.state;
    let emailValid = true;
    let errorMsg = { ...this.state.errorMsg };

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      emailValid = false;
      errorMsg.email = "Invalid email format";
    }

    this.setState({ emailValid, errorMsg }, this.validateForm);
  };

  validatePassword = () =>{
    const { password } = this.state;
    let passwordValid = true;
    let errorMsg = {...this.state.errorMsg}

    if(password.length < 8){
    let passwordValid = false;
      errorMsg.password = "Password should have at least 8 characters"
    }

    this.state({passwordValid, errorMsg})
  }

  confirmPassword  = () =>{
    const { confirmPassword, password } = this.state.confirmPassword
    let passwordConfirmValid = true; 
    let errorMsg = {...this.state.errorMsg}

    if(password !== confirmPassword){
    let passwordConfirmValid = false; 
        errorMsg.passwordConfirm = "Password do not match"
    }

    this.state({passwordConfirmValid, errorMsg})
    
  }
4

1 回答 1

1

基于类的组件的生命周期函数可以接受在状态更新setState调用的第二个参数回调函数。

设置状态

setState(updater, [callback])

它通常用于做一些简单的事情,比如记录更新的状态。

this.setState({ value }, () => console.log('new value', this.state.value);

我认为通常应该避免这种情况,如果您需要发出任何副作用,例如验证表单数据,那么应该使用常规的组件生命周期方法。componentDidUpdate处理更新的状态或道具。

从文档

第二个参数 tosetState()是一个可选的回调函数,一旦setState完成并重新渲染组件就会执行。通常我们建议使用componentDidUpdate()这种逻辑。

在您的情况下,this.setState({ usernameValid, errorMsg }, this.validateForm);函数validateForm引用作为回调传递,并在状态更新后调用。

于 2020-11-21T07:30:12.153 回答