编程新手,我非常感谢在渲染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 回答
setInterval
中函数中的this
不是来自ComponentWillMount
的this
..这就是它失败的原因 . 做类似的事情:在调用setInterval然后再调用之前
您可以阅读有关此关键字here的更多信息 .