简体   繁体   English

在计时器上循环显示/隐藏React组件

[英]Loop through showing/hiding React components on a timer

I'm trying to show or hide a series of "pages" on a timer; 我试图在计时器上显示或隐藏一系列“页面”; in other words every x seconds, render a new group of components. 换句话说,每隔x秒渲染一组新的组件。

const PAGES = [[<Component1 />, <Component2 />], [<Component3 />, <Component4 />]];

export default class MyDashboard extends Component {
  constructor(props) {
    super(props);
    this.state = { index: -1 };
  }

  renderPages() {
    console.log(this.state.index);
    return PAGES[this.state.index];
  }

  setIndex() {
    let index = this.state.index > PAGES.length ? 0 : this.state.index + 1;
    this.setState({ index: index });
  }

  componentDidMount() {
    this.loop = setInterval(this.setIndex(), 3000);
  }

  componentWillUnmount() {
    clearInterval(this.loop);
  }

  render() {
    return <Dashboard layout={CustomLayout}>{this.renderPages()}</Dashboard>;
  }
}

I'm using the Dashbling framework, but essentially I have an array, PAGES , which is a list of arrays. 我正在使用Dashbling框架,但实际上我有一个数组PAGES ,它是数组的列表。 (I've verified that you can indeed render an array of components, so that's not a problem.) (我已验证您确实可以渲染一组组件,所以这不是问题。)

I'm using the state to store the index , updated with setIndex() , which will increase until it surpasses PAGES.length at which point it will reset to 0. 我正在使用状态存储index ,并用setIndex()更新,该index将增加直到超过PAGES.length为止,此时它将重置为0。

I put setIndex() inside setInterval() in the hopes that it would call it every x seconds, thus displaying a new group of components, but it only displays the first page, then stops. 我将setIndex()放在setInterval()内,希望它每隔x秒调用一次,从而显示一组新的组件,但只显示第一页,然后停止。 Any help would be appreciated. 任何帮助,将不胜感激。

You want this: 你要这个:

this.loop = setInterval(() => this.setIndex(), 3000);

not this 不是这个

this.loop = setInterval(this.setIndex(), 3000);

setInterval expects a function as its first argument. setInterval需要一个函数作为其第一个参数。 You are committing a common mistake of passing it the return value of the function (which is undefined ), while calling it just once when the component mounts. 您犯了一个常见错误,即在组件安装时仅一次调用它的函数的返回值undefined )。

Just remove those parentheses: 只需删除这些括号即可:

componentDidMount() {
    this.loop = setInterval(this.setIndex, 3000);
}

except that the value of this will be lost inside the setIndex method when it is called, so in fact you will also need to ensure the correct this is passed. 除了价值this会丢失内部setIndex方法被调用时,所以实际上你还需要确保正确this传递。 You can do this using the bind method, or as shown below, with an arrow function: 您可以使用bind方法或如下所示通过箭头函数来执行此操作:

componentDidMount() {
    this.loop = setInterval(() => this.setIndex(), 3000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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