Everyone has at least one best friend, someone you meet at a turning point in your life and marvel at how different or similar you are. "-- Movie UntouchableCopy the code

SetState can be written in two categories

  1. setState(updater, [callback])

The first argument is an updater function; The second argument is a callback function (optional)

The following is an example:

this.setState((prevState, props) => {
  return {counter: prevState.counter + props.step};
});
Copy the code

The format of the updater function is fixed. The function takes a state as the first argument and (optionally) the props at which the update was applied as the second argument. The setState objects are passed to the function automatically

Changing switch state variables often uses updater to change state, for example:

this.setState(prevState => ({ isToggleOn: ! prevState.isToggleOn }));Copy the code
  1. setState(stateChange, [callback])

The first argument is an object; The second argument is also a callback function (optional)

The following is an example:

this.setState({number: 2})
Copy the code

This is the most common way to change state.

SetState () stuffs the changes that need to be handled into the component’s state object and tells the component and its children that they need to be rerendered with the updated state. This is the primary way to update the user interface in response to event handling and server response.

Think of setState() as a request rather than an immediate command to update the component. React might delay it for better performance and update the components all at once later. React does not guarantee immediate results after setState.

SetState () does not update the component immediately. It could be batch processing or delayed updates. This makes it a potential pitfall to read this.state immediately after calling setState(). Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), where each method is guaranteed to fire after the update is applied. If you need to set states based on previous states, read the description of the updater parameter below.


The state assignment

The following is the assignment of state, divided into three cases:

  1. Assignment in the usual case

Applicable types are: numbers, strings, Booleans, null, undefined. The following is an example:

this.setState({
  count: 1,
  title: 'React',
  success: true
})
Copy the code
  1. Assignment of an array type

If you have a state books of array type, use the concat method of array or ES6’s spread syntax when adding a book to books:

Var books = this.state. Books; var books = this.state. this.setState({ books: books.concat(['three body']); }) {this.setState(preState => ({books: prestate.books.concat ([);}) {this.setState(preState => ({books: prestate.books.concat ([);'three body']); SetState (preState => ({books: [... prestate.books,'three body'];
}))
Copy the code

Use the slice method of arrays when snatches elements from books as new states. (Same with arrays returned by splice.)

Var books = this.state. Books; Enclosing setState ({books: books. Slice (1, 3); }) this.setstate (preState => ({books: prestate.books.slice (1,3); }))Copy the code

When some elements are filtered from books as new states, use the filter method of the array:

Var books = this.state. Books; this.setState({ books: books.filter(item => {returnitem ! ='three body'; }); }) this.setState(preState => ({books: prestate.books.filter (item => {returnitem ! ='three body'; 
  });
}))
Copy the code

Do not use push, POP, shift, unshift, etc., to change the state of the array type, because these methods are based on the original array, while concat, Slice, splice, filter can return a new array.

  1. Assignment of an object type

Use ES6’s Object.assgin method

Var owner = this.state.owner; var owner = this.state.owner; var owner = this.state. this.setState({ owner: Object.assign({}, owner, {name:'Jason'}); This.setstate (preState => ({owner: object.assign ({}, prestate. owner, {name: object.assign ({}, preState.'Jason'});
}))
Copy the code

Using object Spread Properties syntax

Var owner = this.state.owner; var owner = this.state.owner; this.setState({ owner: {... owner, name:'Jason'}; SetState (preState => ({owner: {... preState.owner, name:'Jason'};
}))
Copy the code

This. SetState update mechanism

Each time setState generates a new state, it will be stored in a queue, and it will determine whether to update this.state directly or put it in the dirtyComponent based on the isBathingUpdates variable. IsBatchingUpdates is false by default, which means that setState will update this.state. However, when React calls batchedUpdates before calling the event handler, this function will change isBatchingUpdates to true. The result is that setState controlled by React event handlers will not synchronize this.state.