简体   繁体   中英

React setState doesn't work as I expected

I making a form validation on the page. In one of the tutorials I found a validation method that works correctly but I don't understand one thing. I declare a variable before the class that stores the object with the default input values. When the field is wrong, the corresponding property is modified, while after correctly filling the form the fields are cleared to default values (errors properties becomes empty).

I don't understand the moment when state is set to the default values. Since the initialState object is a reference type, it should have different values after their change in the validate method.

For example, when I assign a string to the usernameError property, I expected this value to remain in this object. Meanwhile, when I do it:

this.setState(initialState);

Form errors will be cleared.

Shortened code:

const initialState = {
 username: "",
 surname: "",
 email: "",
 usernameError: "",
 surnameError: "",
 emailError: "",
};

class Contact extends React.Component {
 constructor(props) {
  super(props);
  this.state = initialState;
  this.handleSubmit = this.handleSubmit.bind(this);
 }

validate() {
let usernameError = "";

if (!this.state.username) {
  usernameError = "Fill in the missing field";
}

if ( usernameError ) {
  this.setState({ usernameError });
  return false;
}

return true;
}

handleSubmit(e) {
  e.preventDefault();

  const isValid = this.validate();
  if (isValid) {
  this.setState(initialState);
  }
}

handleChange = (event) => {
this.setState({
  [event.target.name]: event.target.value,
 });
};

render() {
  // contact form...
}

What you see is the correct behavior. You have to think of this.state = initialState as the new copy creation of initialState object. Because if its just the reference to initialState object, react state object will have no power to deal with state properties. So, to make your code working as per expectations, you have to make these objects separate, or create a copy explicitly. To reset errors, update the state as this.setState({usernameError:''}); Or in the other case of initialState the result will be same but you will be confused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM