Tag Archives: Cannot update during an existing state transition (such as within `render`). …

Three common ways of react event binding and solution can’t update during an existing state transition (such as within ‘render’)

Front end developers must read! Starting from scratch, teach you to build a low code website platform in stages>>>

In react component, the context of each method will point to the instance of the component, that is, automatically bind this as the current component. Moreover, react will cache this kind of reference to optimize CPU and memory. When using ES6 classes or pure functions, this kind of automatic binding no longer exists. We need to implement this binding manually

1. Bind method. This method can help us bind this in the event handler and pass parameters to the event handler, as shown in the following figure

Bind method binding

2. Bind arrow function. Arrow function is not only the “syntax sugar” of function, it also automatically binds this which defines the scope of this function, so we don’t need to use bind method for it, as shown in the figure below:

Arrow function 1

It can also be the following:

class App extends Component {

handleClick(e) { console.log(e); }

render() {return < button onClick={() => this.handleClick()}> Test</ button>}

}

3. Declaration in constructor. This binding is completed in the component constructor. The advantage of this binding method is that it only needs to bind once, and it does not need to perform binding operation every time the event listener is called

Constructor inner declaration

These are three ways to bind events. I personally think the third one is better. Only one binding operation is needed to optimize performance

Finally, an example of rendering error is attached as follows:

Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state

The above prompt shows that the event is not bound to this instance. Just solve it in the above three ways

I have little talent and shallow learning. If there is something wrong, please give me more advice and make progress together