React Component方法在不调用的情况下调用自身?

时间:2016-11-24 15:53:37

标签: javascript reactjs

这张照片旋转木马工作正常。每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 .

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

===============整个代码在这里=========================== < / p>

  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')
);

谢谢!!!

2 个答案:

答案 0 :(得分:1)

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

因此,当React首次创建组件时,将调用 componentDidMount ;这将关闭你的 setInterval

答案 1 :(得分:1)

来自React Spec

  在组件出现后立即调用

componentDidMount()   安装。需要DOM节点的初始化应该放在这里。如果你   需要从远程端点加载数据,这是一个好地方   实例化网络请求。在这种方法中设置状态会   触发重新渲染。