React

[React] state와 setState

tonirr 2020. 7. 22. 00:39

초기값을 정해주고자 할 때 constructor의 state에 지정해준다.

  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

 

이벤트를 통해 state의 초기값을 바꾸고자 한다면 this.setState를 사용한다.

단, onClick등 함수 내에서 state의 값을 바꾼다면 this를 인식하지 못하므로 함수뒤에 .bind(this)를 붙여 해당 컴포넌트를 인식시켜준다.

 

  componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }