简体   繁体   中英

React state gets "corrupted"

I am working on a simple React.JS frontend piece.

I essentially have a browsing SPA for historical data. The design has a bunch of filters that I need to populate one at a time, starting the top one in my logic hierarchy.

I do something like:

  componentWillMount() {
    if (!this.props.advertisers) {
      this.props.loadAdvertisers();
    }
  }

Once advertisers array has been loaded, I map it to options of a select component (using react-select ), set the selection to the first item in the list and load the next list - campaigns .

As far as I understand, the best way to do this is still componentWillReceiveProps() and I am a little perplexed how this should be done differently, given that componentWillReceiveProps is being phased out.

My code looks like:

componentWillReceiveProps(nextProps) {
  if (nextProps.advertisers && !this.props.advertisers) {
    const advertiser = nextProps.advertisers[0];
    this.setState({
      advertiser: {
        value: advertiser['id'],
        label: advertiser['name']
      }
    });
    nextProps.loadCampaigns(advertiser['id']);
  }
  // if campaigns list changed, reload the next filtered array
  if (nextProps.campaigns && this.props.campaigns !== nextProps.campaigns) {
    ...
  }

This worked fine, until I decided to add a loading indicator. I mapped state's loading property eg for campaigns it gets exposed via this.props.campaignsLoading then do:

return (this.props.campaignsLoading || this.props...Loading || ...) ? 
       <ProgressIndicator> : <MainContentPanel>

The problem is now, my state does not get set correctly inside componentWillReceiveProps() .

The project is using @rematch and I initially tried this with @rematch/loading plugin and when the problem happened, thought the plugin does it wrong, somehow. Then, I mapped loading properties manually, and just added two more dispatch es to manually set the loading flag .

All the props are being set/unset correctly, but my state is not being set and nothing works. Any suggestions?

When you do

if (nextProps.advertisers && !this.props.advertisers) {

You are not comparing the next and the previous props. "this.props.advertisers" is probably already set so you never go into the setState line. Although using componentWillReceiveProps is no longer the recommended way to go ( You Probably Don't Need Derived State ), what you probably want to do roughly is:

if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {

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