The state and the props
state:
- Updating state with setState triggers dom updates
- In class components, state can only be updated in Construct
- Update of state is asynchronous: setState does not change immediately after it is called; it is an asynchronous operation.
Is setState synchronous or asynchronous? Synchronous execution and asynchronous processing of data
So how do I get the updated value? SetState has a second callback argument, in which the updated data can be retrieved
setState({}, () = >{dom updated data})Copy the code
When there are consecutive setstates in the code, only the value of the last setState is taken for the following setState method
<button
onClick={() = > {
this.setState({count: this.state.count + 1})
this.setState({count: this.state.count + 2})
}}
>add</button>
Copy the code
How much does count increase with each click? I’m going to add 2 every time. The value that this.state.count depends on will not be the first value after setState + 1 is executed. It’s the initial value of the life cycle
So how do I make it all execute and depend on the previous setState? Replace the setState argument with a function
<button
onClick={() = > {
this.setState((state, props) = > ({count: this.state.count + 1}))
this.setState((state, props) = > ({count: this.state.count + 2}))
}}
>add</button>
Copy the code
The first argument to the function is the state value after the previous setState. The second parameter is props,(the previous props or the current props?).
Note: Do not rely on the current state, calculate the next state
props:
- Data passed from parent to child
- All props are read-only
The event processing
React event handlers cannot prevent default behavior by returning false. For event handlers, we usually extract this as a class method. At this point, we must pay attention to the pointing problem of this. There are two methods: (1) Bind this in Construct
class C extends React.component {
constructor() {
this.eventHandle = this.eventHandle.bind(this)}}Copy the code
(2) Use class fields and arrow functions
class C extends React.component {
eventHandle = (e) = >{}}Copy the code
The event object
React event objects are composite objects. You can use e.ativeEvent to access native event objects by knowing:
- E.target is the element where the event occurs.
- E.currenttarget is the element bound to the event