20.10.15 [React Review]

박종찬·2020년 10월 15일
0

TIL

목록 보기
36/89
post-thumbnail

하위 컴포넌트에 이벤트 속성을 전달하는 법을 자꾸 햇갈려서 상태 변경하는 것과 이벤트 처리, 리프팅? 복습을 했다.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      num: 0,
      curTime: new Date(),
      bgs: []
    }
    this.time = {
      curTime: new Date()
    }
  }



  componentDidMount() {
    setInterval(() => { this.tick() }, 500);
  }

  getImg() {
    fetch(`https://api.unsplash.com/photos/?client_id=${myAPI}`)
      .then(res => res.json())
      .then((data) => {
        this.setState({
          bgs: data
        })
      })
  }

  handlePLUS() {
    this.setState({
      num: this.state.num + 1
    })
  }

  handleMINUS() {
    this.setState({
      num: this.state.num - 1
    })
  }

  tick() {
    this.setState({
      curTime: new Date()
    });
  }

  render() {
    return (
      <div className="App">
        <div>
          <h1>
            {this.state.curTime.toLocaleTimeString()}
          </h1>
          <button onClick={this.handlePLUS.bind(this)}>PLUS</button>
          <button onClick={this.handleMINUS.bind(this)}>MINUS</button>
          <span className="number">{this.state.num}</span>

          <button onClick={this.getImg.bind(this)}>이미지 받아오기</button>
          <Bg photos={this.state.bgs} />

        </div>
      </div>
    );
  }
}

문제가 발생했는데.. 시간이 계속 setInterval로 수정이 되니 Life Cycle이 돌아가서 state가 계속 갱신된다..

profile
반가워요! 사람을 도우는 웹 개발자로 성장하기! :)

0개의 댓글