简体   繁体   中英

How to re-rendering react class component when state is changed

New to both react and javascript and was wondering how do we re-render the component? I need to make sure that the details (Eg badge counter) in button component re-render everytime we get a change in facets. I see some older attempts by other developers to set state but it doesn't seem to be working so i need some guidance on the following.

  1. How to detect when there is a change in facets?
  2. How do we re-render the component everytime we get a change in facets?
class SearchResult extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      _query: props.query,
      _facets: props.facets,
      _hasLoaded: false,
    };
  }

  render() {
    const {
      onEntityClick, facets, entity, total, pagingTotal, isFilterSubmitted, loading, query,
    } = this.props;
    const {
      _query, _facets, _hasLoaded,
    } = this.state;
    if ((_query !== query && query !== '*') && !loading) {
      this.setState({
        _query: query,
        _facets: facets,
      });
    }
    if ((_query === query && query === '*' && !_hasLoaded) && !loading) {
      this.setState({
        _query: query,
        _facets: facets,
        _hasLoaded: true,
      });
    }
    return (
      <Fragment>
        <ButtonComponent
          btnTheme="gray"
          size="small"
          label="Note"
          icon="note"
          // eslint-disable-next-line no-nested-ternary
          badgeCounter={!loading ? entity === 'note' && isFilterSubmitted ? pagingTotal : _facets.note : 0}
          disabled={entity === 'note'}
          callbackFunc={() => onEntityClick('note')}
        />
      </Fragment>
    );
  }
}

You're making an antipattern in your code:

this.setState() should never be called inside the render() function.

Instead, what you would like to do is check componentDidUpdate() :

componentDidUpdate(prevProps) {
  if (prevProps.query !== props.query && query !== "*") {
    ...
  }
}

This guarantees a re-rendered so you don't need to worry about "manually" re-rendering.

Also note that props.query as well as other values, don't need to be saved in the component state unless you need a modified copy of it -- that's what didUpdate will do.

You can try componentWillReceiveProps LC method, if there is a change in props and set the state(re-render) of the component acc. to that change.

UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    console.log(nextProps.facets);
    console.log(this.state._facets);
    if (nextProps.facets !== this.state._facets) {
        this.setState({
            _facets: 'YES'
        })
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM