Programing

React 앱의 setInterval

lottogame 2020. 9. 13. 11:39
반응형

React 앱의 setInterval


나는 여전히 React에서 상당히 새롭지 만 천천히 진행하면서 내가 붙어있는 무언가를 만났습니다.

저는 React에서 "타이머"컴포넌트를 구축하려고하는데, 솔직히 제가이 일을 제대로하고 있는지 (또는 효율적으로)하고 있는지 모르겠습니다. 아래에있는 내 코드에서, 나는 개체를 반환 상태를 설정 { currentCount: 10 }하고 놀겠다는 거를하고있다 componentDidMount, componentWillUnmount그리고 render나는 10에서 9 "카운트 다운"의 상태를 얻을 수 있습니다.

두 부분으로 구성된 질문 : 내가 잘못한 것은 무엇입니까? 그리고 ( componentDidMount&를 사용하는 대신) setTimeout을 사용하는 더 효율적인 방법이 componentWillUnmount있습니까?

미리 감사드립니다.

import React from 'react';

var Clock = React.createClass({

  getInitialState: function() {
    return { currentCount: 10 };
  },

  componentDidMount: function() {
    this.countdown = setInterval(this.timer, 1000);
  },

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

  timer: function() {
    this.setState({ currentCount: 10 });
  },

  render: function() {
    var displayCount = this.state.currentCount--;
    return (
      <section>
        {displayCount}
      </section>
    );
  }

});

module.exports = Clock;

코드에 4 가지 문제가 있습니다.

  • 타이머 방법에서는 항상 현재 카운트를 10으로 설정합니다.
  • 렌더링 메서드에서 상태를 업데이트하려고합니다.
  • setState실제로 상태를 변경하는 방법을 사용하지 않습니다.
  • 상태에 intervalId를 저장하지 않습니다.

이 문제를 해결해 보겠습니다.

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

이로 인해 타이머가 10에서 -N으로 감소합니다. 타이머를 0으로 낮추려면 약간 수정 된 버전을 사용할 수 있습니다.

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

다음을 사용하여 10 초 카운트 다운 업데이트 class Clock extends Component

import React, { Component } from 'react';

class Clock extends Component {
  constructor(props){
    super(props);
    this.state = {currentCount: 10}
  }
  timer() {
    this.setState({
      currentCount: this.state.currentCount - 1
    })
    if(this.state.currentCount < 1) { 
      clearInterval(this.intervalId);
    }
  }
  componentDidMount() {
    this.intervalId = setInterval(this.timer.bind(this), 1000);
  }
  componentWillUnmount(){
    clearInterval(this.intervalId);
  }
  render() {
    return(
      <div>{this.state.currentCount}</div>
    );
  }
}

module.exports = Clock;

Hooks를 사용하여 10 초 카운트 다운이 업데이트되었습니다 (클래스를 작성하지 않고도 상태 및 기타 React 기능을 사용할 수있는 새로운 기능 제안. 현재 React v16.7.0-alpha에 있습니다).

import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

const Clock = () => {
    const [currentCount, setCount] = useState(10);
    const timer = () => setCount(currentCount - 1);

    useEffect(
        () => {
            if (currentCount <= 0) {
                return;
            }
            const id = setInterval(timer, 1000);
            return () => clearInterval(id);
        },
        [currentCount]
    );

    return <div>{currentCount}</div>;
};

const App = () => <Clock />;

ReactDOM.render(<App />, document.getElementById('root'));

감사합니다 @dotnetom, @ greg-herbowicz

"this.state is undefined"를 반환하는 경우-bind timer function :

constructor(props){
    super(props);
    this.state = {currentCount: 10}
    this.timer = this.timer.bind(this)
}

참고 URL : https://stackoverflow.com/questions/36299174/setinterval-in-a-react-app

반응형