关于react class组件setState的问题

Question about react class component setState

我不明白这部分代码:

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

如果我们在状态中更新usernameValiderrorMsg,那么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})
    
  }
基于

Class 的组件的 setState 生命周期函数可以采用第二个参数回调函数,在 状态更新后调用

setState

setState(updater, [callback])

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

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

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

来自文档

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

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