생활코딩 React #3

이동현·2021년 6월 24일
0

생활코딩 리액트

목록 보기
3/6
post-thumbnail

State

컴포넌트 내부적으로 사용되며 사용자는 알 필요도 없고 알아서도 안 되는
것이 State이다.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      subject: { title: "WEB", sub: "World Wide Web!" },
    };
  }

  render() {
    return (
      <div className="App">
        //이 Subject가 state를 사용한 코드
        <Subject
          title={this.state.subject.title}
          sub={this.state.subject.sub}
        ></Subject>
        <TOC></TOC>
        //아래 코드가 이전의 하드코딩인 상태임
        <Content title="HTML" desc="HTML is language."></Content>
      </div>
    );
  }
}

이렇게 state를 씀으로써 얻게 되는 효용이 뭐가 있을까? 왜 쓰는 것일까?

아직은 모르겠다.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      subject: { title: "WEB", sub: "World Wide Web!" },
      //여러 종류의 경우 이런 식으로 state를 배열로 만든다.
      contents: [
        { id: 1, title: "HTML", desc: "HTML is hyper text markup..." },
        { id: 2, title: "CSS", desc: "CSS is desing..." },
        {
          id: 3,
          title: "Javascript",
          desc: "Javascript is for interactive...",
        },
      ],
    };
  }
  ...
}

//아래의 코드처럼 state를 사용한다.
class TOC extends Component {
  render() {
    let lists = [];
    let data = this.props.data;
    let i = 0;
    while (i < data.length) {
      lists.push(
        <li key={data[i].id}>
          <a href={"/content" + data[i].id}>{data[i].title}</a>
        </li>
      );
      i = i + 1;
    }
    return (
      <nav>
        <ul>{lists}</ul>
      </nav>
    );
  }
}
profile
Dom Hardy : 멋쟁이 개발자 되기 인생 프로젝트 진행중

0개의 댓글