React中通过字符串数组的无限循环

时间:2017-03-01 21:10:20

标签: reactjs

编程新手,我非常感谢在渲染React组件方面提供一些帮助。我有一个字符串数组,我想在无限循环中每隔5秒显示该数组中的每个字符串。我试图设置状态时遇到的错误是#t; this.setState不是函数'。我倾向于认为我使用了错误的生命周期方法或存在绑定问题,但我迷失了方向。下面是代码。我真的很感激一些帮助。

import React, {Component} from 'react';

class Home extends Component{
  constructor(props){
    super(props);
    this.state = {
      service: ''
    }
  }
  componentDidMount(){
    var services = ['Delivering professional and personalized care to your loved ones','Home visits with a personalized health plan', 'Transition Assistace', 'Advocacy and Guidance', 'Respite Care']
    let i=0;
    setInterval(function(){
      console.log('set interval working');
      const currentService = services[i];
      this.setState({
        service: currentService
      })
      i++;
      if(i>=services.length){
        i = 0;
      }
    }, 5000);
  }
  render(){
    console.log('this', this.state.service);
    return(
      <div className="home">
        <div className="profile-img"></div>
        <div className="mission">
          <div className="overlay">
            <p>{this.state.service}</p>
          </div>
        </div>
      </div>
    )
  }
}
export default Home;

1 个答案:

答案 0 :(得分:3)

this中您的函数中的setInterval不是来自this的{​​{1}} ..这就是失败的原因。做类似的事情:

ComponentWillMount

在调用setInterval然后再调用

之前
var that = this;

您可以详细了解此关键字here