2017-07-17 21 views
0

我是新来对付js的。我创建了一个简单的滑块组件。它正在工作,但我想问问是否有正确的方法来调用该方法?至于我在构造函数中调用它的那一刻。我真的很感激任何建设性的批评。谢谢。在哪里调用反应组件中的方法?

import React from 'react'; 

export default class Slider extends React.Component { 

    constructor() { 
     super(); 

     this.state = { 
      current: 4 
     }; 

     this.current = this.state.current; 

     setTimeout(() => { 
      this.animate(); 
     }, 5000); 
    } 

    animate() { 
     this.getCurrent(); 
     this.setState({ 
      current: this.current 
     }); 
    } 

    getCurrent() { 
     this.current = (this.current >= this.props.slides.length - 1) ? 0 : this.current + 1; 
     return this.current; 
    } 

    render() { 
     var slides = this.props.slides; 
     var slideList = slides.map((slide, index) => { 
      let slideClass = (index == this.state.current) ? 'slider-item active' : 'slider-item'; 
      return <div className={slideClass} key={index}><span>{slide}</span></div>; 
     }); 

     return (
      <div className="slider-component">{slideList}</div> 
     ) 
    } 
} 
+1

我认为更好的选择将使用'componentDidMount'函数。 –

回答

2

做,在componentDidMount这样的:

componentDidMount() { 
    this.timer = setTimeout(() => { 
     this.animate(); 
     this.timer = undefined 
    }, 5000); 
} 

但是不要忘记清除计时器上卸载这样的:

componentWillUnmount() { 
    if (this.timer) { 
    clearTimeout(this.timer) 
    } 
} 

否则代码将打破,如果这部分是在卸载前5000ms,因为它会尝试在未安装的组件中执行setState

+0

我复制粘贴这段代码但它不再工作? –

+0

伟大的工作。只是错字错误:) –

+0

不要忘记'componentWillUnmount'部分。这同样重要。 –

1

调用它在componentDidMount()

1

一个构造非常应该只是构建应在页面后习惯,如果你想要的东西上运行的对象“摩的”我想将它添加到ComponentDidMount()因为如果你已经将滑块构建为自己的组件,那么每当它被“激活”就可以运行该方法一次。

+0

谢谢!是的,我看到它只运行一次。 –

相关问题