다시 React! -6 State

문규찬·2021년 8월 23일
0
post-thumbnail

Clock.js

function Clock(props) {
  console.log(props);
  return (
    <div>
      <h1>Hellow</h1>
      <h2>It is {props.date.toLocaleTimeString()}</h2>
    </div>
  );
}

이전에 작성했던 Clock 컴포넌트입니다.
Clock 이 타이머를 설정하고 매 초 UI를 업데이트 하는 것은 Clock 의 구현 세부사항이어야 합니다.
이상적으로 Clock 은 한번만 작성하고 자체적으로 업데이트 시키려고 합니다.

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

이를 실행하기 위해 state를 추가해주어야 합니다.

함수형을 class로 변환

  1. Create an ES6 class, with the same name, that extends React.Component.
  2. Add a single empty method to it called render().
  3. Move the body of the function into the render() method.
  4. Replace props with this.props in the render() body.
  5. Delete the remaining empty function declaration.
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

The render method will be called each time an update happens

Class에 Local State 추가하기

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }
  render() {
    return (
      <div>
        <h1>Hellow</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}</h2>
      </div>
    );
  }
}

export default Clock;
  1. constructor (이니셜 스테이트) 를 추가해줍니다.
 constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  1. 클래스 컴포넌트는 항상 props 와 함께 constructor 를 호출합니다.

🔴 State 바르게 사용하기

1. State를 직접 수정하지 마세요

Wrong ❌
this.state.comment = "hello"

이 코드는 컴포넌트를 다시 렌더링 하지 않습니다.

Correct ⭕️
this.setState({ commment : "hello" })

2. State Updates May Be Asynchronous

this.props 및 this.state 가 비동기로 업데이트될 수 있기 때문에, 다음 state 계산을 위해 그들의 value에 의존해서는 안됩니다.

  clickCount = () => {
  
    🔴// this.setState(
    //   { count: this.state.count + 1 },
    //   console.log("first state changed!")
    // );
    // this.setState(
    //   { count: this.state.count + 1 },
    //   console.log("second state changed")
    // );
    
    
    
    🟠this.setState(
      (state) => ({ count: state.count + 1 }),
      console.log("first State Changed!!")
    );
    this.setState(
      (state) => ({ count: state.count + 1 }),
      console.log("second State Changed!!")
    );
  };

🔴 setState를 두번 호출하였습니다. {count:this.state.count +1 } 로 버튼 클릭시 +2가 되어야 하지만 console은 second state changed가 찍히지만 화면에 count는 +1 만 적용됩니다.

🟠 setState 에서 화살표 함수를 호출하였습니다. state를 받아 {count : state.count +1 } 을 해주어 두번의 호출로 화면의 count 는 클릭시 +2 씩 올라갑니다.

⭐️ 사실 ⬆️ 이 부분 이해하기 어렵.....다

3. State Updates are Merged

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

예를 들어, state는 여러 독립적인 변수를 가질 수 있습니다

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

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

그런 다음 개별 setState() 를 호출하여 아이템을 각각 업데이트할 수 있습니다.

데이터는 아래로 흐른다

데이터가 아래로 흐릅니다.
부모 컴포넌트나 자식 컴포넌트는 특정 컴포넌트의 state 유무를 알 수 없으며 해당 컴포넌트가 함수나 클래스로 선언되었는 지 알 수 없습니다.

이는 state가 로컬이라고 부르거나 캡슐화된 이유입니다. 컴포넌트 자신 외에는 접근할 수 없습니다.

컴포넌트는 자신의 state를 자식 컴포넌트에 props 로 내려줄 수 있습니다.

0개의 댓글