V
V
Vanya Huk2018-05-31 01:00:31
React
Vanya Huk, 2018-05-31 01:00:31

Why is shouldComponentUpdate not working correctly after using setState in a function?

there is a component

import React, {Component} from 'react';

import RaisedButton from 'material-ui/RaisedButton';

class BrandModels extends Component {

  constructor(props) {

    super(props);

    this.state = { items : [ undefined ] }


  }


  shouldComponentUpdate( nextProps, nextState ) {

    console.log( nextState.items, this.state.items )

    if ( nextState.items != this.state.items)
      return true;

    return false;

  }

  addGroup(){

    let items = this.state.items;

    items.push( undefined );

    this.setState({ items : items })

  }
  render() {
    return (
      <div
        className={country_brand_mod_list">
        
        <div className="row">
          <div className="col-12">
            <RaisedButton
              label={window._sharedData.loc.app.add}
              primary={true}
              onClick={this.addGroup.bind(this)}
            />
          </div>
        </div>
      </div>
    )
  }

}

export default BrandModels;

after clicking on the button, 1 element is added to the array of the items
state , but, in shouldComponentUpdate nextState.items , for some reason it is always equal to this.state.items
5b0f1efbd1753295757972.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-05-31
@vanyahuk

in shouldComponentUpdate nextState.items for some reason is always equal to this.state.items

Of course - you do not create a new array.
Replace
let items = this.state.items;
items.push( undefined );

on the
let items = [ ...this.state.items, undefined ]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question