-->

Refreshing a setInterval in React

2019-07-26 20:53发布

问题:

This is based on the answer given here:

I'm having trouble resetting a setInterval.

As of now the following works. I have a prop called mediaList which contains an object array of images. When changeActiveMedia is called, the object position is moved to the next one in the list.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeMediaIndex: 0 };
  }

  componentDidMount() {
    setInterval(this.changeActiveMedia.bind(this), 5000);
  }

  changeActiveMedia() {
    const mediaListLength = this.props.mediaList.length;
    let nextMediaIndex = this.state.activeMediaIndex + 1;

    if(nextMediaIndex >= mediaListLength) {
      nextMediaIndex = 0;
    }

    this.setState({ activeMediaIndex:nextMediaIndex });
  }

  renderSlideshow(){
    const singlePhoto = this.props.mediaList[this.state.activeMediaIndex];
      return(
        <div>
          <img src={singlePhoto.url} />
        </div>
      );
    }

  render(){   
    return(
      <div>
          {this.renderSlideshow()}
      </div>
    )
  }
}

My problem arises here.

I have logic that can change the number of objects in the list, mediaList.

This becomes a problem because since the interval only updates once every 5000 seconds, if the nextMediaIndex within that time is 2, and then I all of a sudden update the mediaList to have only 1 item, I run into an error since mediaList[2] would not exist.

So my question is, is there a way to RESET and CLEAR the setInterval whenever this.props.mediaList is updated?

回答1:

window.setInterval returns an id which identifies an Interval timer. You can use it in conjunction with clearInterval to cancel the interval.

this.interval = setInterval(...);
...
clearInterval(this.interval);

you can use componentWillReceiveProps as kind of a generic method of checking to see if mediaList has changed. for example:

componentWillReceiveProps(nextProps) {
    if (nextProps.mediaList !== this.props.mediaList) {
        clearInterval(this.interval);
    }
}