首页 文章

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

提问于
浏览
1

编程新手,我非常感谢在渲染React组件方面提供一些帮助 . 我有一个字符串数组,我想在无限循环中每隔5秒显示该数组中的每个字符串 . 我试图设置状态时遇到的错误是'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 回答

  • 3

    setInterval 中函数中的 this 不是来自 ComponentWillMountthis ..这就是它失败的原因 . 做类似的事情:

    var that = this;
    

    在调用setInterval然后再调用之前

    that.setState()
    

    您可以阅读有关此关键字here的更多信息 .

相关问题