react is a one-way data stream. If you want to change the appearance of an existing component, we can only change the component's props or update the component's state. The most common method we operate in the react project code is the method. The following is a detailed description of the setState method.
<!--more -->
Key points of setState: In order to improve performance, the react framework will collect, merge state updates, and then batch state updates. This mechanism often leads to some unexpected situations.
setState has two types of call:
Passing an object to setState
setState() does not trigger state updates immediately.
// = 1; handleClick = () => { ({demo: 2}); ();// 1 }
1. 🔔Note: It is triggered immediately in addEventListener, setTimeout, and ajax callbacks.
2. SetState will merge and update, which may cause the status update to be lost.
handleClick = () => { ({demo: + 1}); ({demo: + 1}); } //click after demo for2Instead3
To sum up: Do not call methods multiple times in the same code block
react's setState also provides another form of call: (callbackFunc)
((previousState, currentProps) => { return { ...previousState, foo: }; });
This syntax is different from passing objects directly for setState, and will not merge and update.
// demo + 1 handleSyncStateChange = () => { ({ demo: + 1 }); ({ demo: + 1 }); } // demo + 2 handleAsyncStateChange = () => { ((preState, preProps) => { return { demo: + 1 } }); ((preState, preProps) => { return { demo: + 1 } }); }
refs
Async Nature Of setState
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.