Home >Web Front-end >JS Tutorial >A brief introduction to the setState mechanism under React
This article brings you a brief introduction to the setState mechanism under React. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
api analysis: setState(updater, [callback])
updater: update data FUNCTION/OBJECT
callback: callback FUNCTION after successful update
// updater - Function this.setState((prevState, props) => { return {counter: prevState.counter + props.step}; }); // update - Object this.setState({quantity: 2})
Features of setState:
1. Asynchronous: react usually collects a batch of components that need to be updated, and then updates them all at once to ensure rendering performance
2. Problems and solutions caused by shallow merging Objecr.assign()
After using setState to change the state, immediately get the latest through this.state Status
Solution: Obtain
// setState回调函数 changeTitle: function (event) { this.setState({ title: event.target.value }, () => this.APICallFunction()); }, APICallFunction: function () { // Call API with the updated value }
in the callback function of componentDidUpdate or setState. There is a requirement. It needs to be accumulated twice in onClick. If updated using the object method, it will only be added once.
Solution: Use updater function
onClick = () => { this.setState({ index: this.state.index + 1 }); this.setState({ index: this.state.index + 1 }); } // 最后解析为,后面的数据会覆盖前面的更改,所以最终只加了一次. Object.assign( previousState, {index: state.index+ 1}, {index: state.index+ 1}, ) //正确写法 onClick = () => { this.setState((prevState, props) => { return {quantity: prevState.quantity + 1}; }); this.setState((prevState, props) => { return {quantity: prevState.quantity + 1}; }); }
Suggestions:
1. Do not write setstate() in the render() function unless you customize the shouldComponentUpdate method yourself, otherwise it will cause an infinite loop
2 . You cannot directly assign a value to state, and it will not cause render eg: this.state.num = 2
3. When operating on reference objects such as arrays and objects, use methods that return new objects
array: Do not use push, pop, shift, unshift, splice can use concat, slice, filter, extended syntax
object: Object.assgin/extended syntax
setState update mechanism
As shown in the figure: pending queue and update queue
The above is the detailed content of A brief introduction to the setState mechanism under React. For more information, please follow other related articles on the PHP Chinese website!