在React.js中更新道具后的启动间隔

时间:2018-09-13 10:14:18

标签: reactjs

我想在后端数据作为道具输入后触发间隔。 看一下这段代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getAdvert } from "../../actions/advert";
import './_advert.scss';

class Advert extends Component {
  state = { counter: 0 };

  componentDidMount() {
    const { getAdvert } = this.props;

    getAdvert();
  }

  componentWillReceiveProps(nextProps) {
    const { counter } = this.state;

    this.bannerInterval = setInterval(() => {
      this.setState({ counter: counter === Object.keys(nextProps.banners).length - 1 ? 0 : counter + 1 });
    }, 1000) 
  }

  render() {
    const { banners } = this.props;
    const { counter } = this.state;

    return (
      <div className="advert__container">
        <img src={banners[counter] && banners[counter].image_url} alt="advert" />
      </div>
    );
  }
}

const mapStateToProps = ({ banners }) => {
  return { banners };
};

const mapDispatchToProps = (dispatch) => {
  return {
    getAdvert: () => dispatch(getAdvert())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Advert);

因此,您可以看到我尝试在componentWillReceiveProps方法中运行它,因为我认为它可能是依赖传入道具的合适地方。但这行不通。我将只运行一次,并且interval将重复相同的值。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

ComponentWillReceive道具以这种方式使用非常危险。每次收到道具时,您都在设置一个新间隔,而不会存储和取消前一个间隔。 还不清楚如何增加计数器,因为我看到三元数的增加不会增加计数器值的增量。

// This is an example, the lifeCylce callback can be componentWillReceive props
componentDidMount() { 
   const intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
}

componentWillUnmount() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
}

timer = () => {
   // setState method is used to update the state with correct binding
   this.setState({ currentCount: this.state.currentCount -1 });
}