Binding to an event handler that calls setState on ComponentDidMount raises a warning

I am using jQuery to create event bindings in a ReactJS component function componentDidMount, which seems to be the right place for this.

$('body').on('defaultSearchContext.registerQueryEditor', (function(_this) {
  return function(event, component) {
    _this.setState({
      queryEditors: _this.state.queryEditors.concat([component])
    });
  };
})(this));

This code does not actually run on componentDidMount, it just sets up the binding, which later triggers setStatewhen the event fires. However, this generates the following warning every time this event fires, which pollutes my console with dozens of warnings:

Warning: setState (...): cannot be updated during an existing state transition (e.g. within render). Rendering methods should be a pure function of props and status.

setState onEvent componentDidMount, .

, , , , componentDidMount. , , , , , ReactJS. , ReactJS 0.14.3 ( ).

, , React Js onClick . onClick, .

+4
2

. , DOM. React store/dispatcher, Redux Flux ( ). , , , . React, .

, , - . - , , . , , . DOM ; jQuery . .

.

let simpleEventCoordinator = {
  callbacks: new Map(),
  getHandler(eventKey) {
    let handler = this.callbacks.get(eventKey);
    if (!handler) {
      handler = new Set();
      this.callbacks.set(eventKey, handler);
    }
    return handler;
  },
  registerCallback(eventKey, callback) {
    this.getHandler(eventKey).add(callback);    
  },
  removeCallback(eventKey, callback) {
    this.getHandler(eventKey).delete(callback);
  },
  trigger(eventKey, data) {
    this.getHandler(eventKey).forEach(c => c(data));
  }

, nameOfEvent => callback(). , . .

, , , . , :

React.render((
  <div>
    <QueryManager />
    <button onClick={() => simpleEvent.trigger('event')}>{'Update'}</button>
  </div>
), document.body);

  componentDidMount() {
    simpleEvent.registerCallback('event', this.update);
  }
  componentWillUnmount() {
    simpleEvent.removeCallback('event', this.update);
  }
  update() {
    //do some stuff
  }

codepen, .

+1

, , , - , , . , jQuery ? - , .

0

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


All Articles