Why does React throw an error when using the setState method in the class constructor?

I know that when setting the state for a component that is not yet mounted, an error occurs. This explains the error I get from using the setState function, both against explicitly and directly setting the state.

import React, {Component} from 'react';

class SearchBar extends Component {

constructor(props) {
  super(props);

  this.state = {term: ''}; // -> seems to be the agreed means to set   initial state
// this.setState({term: ''}); // -> generates an error
}

render() {
  return (
    <div>
      <input onChange={event => this.setState({term:   event.target.value})}/>
      Value of the input: {this.state.term}
  </div>
);
  }
}

The error I get when I uncomment the second line of this.setState ({term: ''}):

Warning: setState (...): Can only upgrade mounted or mounted components. This usually means that you called setState () on an unmounted component. This is a no-op. Check the component code.

, , , React - , github, : Github Issue # 3878 , Cant React ? setState , , , ? , , , - , ?

+3
1

React state, null, . , React setState . docs:

setState() this.state, . this.state .

setState, .

setState() , shouldComponentUpdate().

, setState() - , , , . , , , , . , .

, , , , null, . React , setState. ES5 , getInitialState. ES6 , constructor ( React ). , React , this.state = {} setState().

+8

Source: https://habr.com/ru/post/1679464/


All Articles