gpt4 book ai didi

javascript - React 组件方法在不调用的情况下调用自身?

转载 作者:行者123 更新时间:2023-11-30 15:41:12 25 4
gpt4 key购买 nike

这个照片轮播效果很好。它每 5 秒更换一次照片。我的问题是 setInterval(this.nextGP, 5000); 如何在不调用 `componentDidMount 的情况下调用自身?这是:

componentDidMount: function () {
this.interval = setInterval(this.nextGP, 5000);
},

在 JavaScript 中:在我们调用外部函数之前,在另一个函数内部调用的函数不会调用。

       function outer(){
anotherFunction();
};
anotherFunction(){
alert("hello");
}
outer(); // We call outer to invoke anotherFunction .

但是在上面的 react 中,setInterval() 调用时没有调用外部函数。

=============== 完整代码在这里 ===========================

  var GUINEAPATHS = [
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-1.jpg',
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-2.jpg',
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-3.jpg',
'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-guineapig-4.jpg'
];

var GuineaPigs = React.createClass({
getInitialState: function () {
return { currentGP: 0 };
},

nextGP: function () {
var current = this.state.currentGP;
var next = ++current % GUINEAPATHS.length;
this.setState({ currentGP: next });
},

interval: null,

componentDidMount: function () {
this.interval = setInterval(this.nextGP, 5000);
},

componentWillUnmount: function () {
clearInterval(this.interval);
},

render: function () {
var src = GUINEAPATHS[this.state.currentGP];
return (
<div>
<h1>Cute Guinea Pigs</h1>
<img src={src}/>

);
}
});

ReactDOM.render(
<GuineaPigs />,
document.getElementById('app')
);

谢谢!!!

最佳答案

生命周期 函数,如 componentDidMount、shouldComponentUpdate 等,在创建和渲染组件时由 React 本身调用。

因此 componentDidMount 将在 React 首次创建组件时调用;这将启动您的setInterval

关于javascript - React 组件方法在不调用的情况下调用自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40790498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com