본문 바로가기

TIL

TIL) 생활코딩 React update

# 배운 것

- 상태가 Object일 때 useState 사용법
1) 배열이 아닌 객체일때

newValue = {...value} -> 복제본 만들기
newValue 변경 -> 새로운 값 push
setValue(newValue)
2) 배열일때

newValue = [...value] -> 복제본 만들기
newValue 변경 -> 새로운 값 push
setValue(newValue)

 

# 복습한 것

-<form> 태그 : 정보를 서버로 전달할 때 사용
ex) <form><input type="text"/></form>
-<p> 태그 : 하나의 문단을 만들 때 사용. 줄바꾸기 기능
-이벤트 핸들러
onSubmit : submit 버튼 클릭했을 때 발생

 

# 느낀 것

react는 참 어렵다. 

state에 따라 동작의 흐름이 달라지니 이를 상상하면서 머릿속으로 굴려보는게 잘 안되네.

여러번 시뮬레이션 하면서 익숙해지는 수 밖에 없을 듯?

import React, { useState } from 'react';

function Article(props) {
  return (
    <article>
      <h2>{props.title}</h2>
      {props.body}
    </article>
  );
}
function Header(props) {
  return (
    <header>
      <h1>
        <a
          href="/"
          onClick={(event) => {
            event.preventDefault();
            props.onChangeMode();
          }}
        >
          {props.title}
        </a>
      </h1>
    </header>
  );
}
function Nav(props) {
  const lis = [];
  for (let i = 0; i < props.topics.length; i++) {
    let t = props.topics[i];
    lis.push(
      <li key={t.id}>
        <a
          id={t.id}
          href={'/read/' + t.id}
          onClick={(event) => {
            event.preventDefault();
            props.onChangeMode(Number(event.target.id));
          }}
        >
          {t.title}
        </a>
      </li>
    );
  }
  return (
    <nav>
      <ol>{lis}</ol>
    </nav>
  );
}
function Create(props) {
  return (
    <article>
      <h2>Create</h2>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const title = event.target.title.value;
          const body = event.target.body.value;
          props.onCreate(title, body);
        }}
      >
        <p>
          <input type="text" name="title" placeholder="title" />
        </p>
        <p>
          <textarea name="body" placeholder="body"></textarea>
        </p>
        <p>
          <input type="submit" value="Create"></input>
        </p>
      </form>
    </article>
  );
}
function Update(props) {
  const [title, setTitle] = useState(props.title);
  const [body, setBody] = useState(props.body);
  return (
    <article>
      <h2>Update</h2>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const title = event.target.title.value;
          const body = event.target.body.value;
          props.onUpdate(title, body);
        }}
      >
        <p>
          <input
            type="text"
            name="title"
            placeholder="title"
            value={title}
            onChange={(event) => {
              setTitle(event.target.value);
            }}
          />
        </p>
        <p>
          <textarea
            name="body"
            placeholder="body"
            value={body}
            onChange={(event) => {
              setBody(event.target.value);
            }}
          ></textarea>
        </p>
        <p>
          <input type="submit" value="Update"></input>
        </p>
      </form>
    </article>
  );
}
function App() {
  const [mode, setMode] = useState('WELCOME');
  const [id, setId] = useState(null);
  const [nextId, setNextId] = useState(4);
  const [topics, setTopics] = useState([
    { id: 1, title: 'html', body: 'html is ...' },
    { id: 2, title: 'css', body: 'css is ...' },
    { id: 3, title: 'javascript', body: 'javascript is ...' },
  ]);
  console.log(topics) 
  // topics는 초기값으로 {id1~3} 갖고있음
  let content = null;
  let contextControl = null;
  if (mode === 'WELCOME') {
    content = <Article title="Welcome" body="Hello, WEB"></Article>;
  } else if (mode === 'READ') {
    let title,
      body = null;
    console.log(topics.length)
    for (let i = 0; i < topics.length; i++) {
      if (topics[i].id === id) {
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    console.log(title, body)
    content = <Article title={title} body={body}></Article>;
    contextControl = (
      <li>
        <a
          href={'/update/' + id}
          onClick={(event) => {
            event.preventDefault();
            setMode('UPDATE');
          }}
        >
          Update
        </a>
      </li>
    );
  } else if (mode === 'CREATE') {
    content = (
      <Create
        onCreate={(_title, _body) => {
          const newTopic = { id: nextId, title: _title, body: _body };
          const newTopics = [...topics];
          newTopics.push(newTopic);
          setTopics(newTopics);
          setMode('READ');
          setId(nextId);
          setNextId(nextId + 1);
        }}
      ></Create>
    );
  } else if (mode === 'UPDATE') {
    let title,
      body = null;
    for (let i = 0; i < topics.length; i++) {
      if (topics[i].id === id) {
        title = topics[i].title;
        body = topics[i].body;
      }
    }
    content = (
      <Update
        title={title}
        body={body}
        onUpdate={(title, body) => {
          console.log(title, body);
          const newTopics = [...topics];
          const updatedTopic = { id: id, title: title, body: body };
          for (let i = 0; i < newTopics.length; i++) {
            if (newTopics[i].id === id) {
              newTopics[i] = updatedTopic;
              break;
            }
          }
          setTopics(newTopics);
          setMode('READ');
        }}
      ></Update>
    );
  }
  return (
    <div>
      <Header
        title="WEB"
        onChangeMode={() => {
          setMode('WELCOME');
        }}
      ></Header>
      <Nav
         //nav 컴포넌트를 실행하게 되면, topics의 값은 변수 {topics}로 할당된다. 
       
     	topics={topics}
       
        //nav 컴포넌트 내에서 onclick 이벤트에의해 onChangeMode 함수가 호출된다.
        //onchagemode 함수는 mode의 상태를 read로 바꾸고, id를 인자값인 _id로 바꾼다.
        //바뀐 상태에서 app 함수는 다시 한 번 실행된다.
        
        onChangeMode={(_id) => {
          setMode('READ');
          setId(_id);
        }}
      ></Nav>
  
      {content}
      <ul>
        <li>
          <a
            href="/create"
            onClick={(event) => {
              event.preventDefault();
              setMode('CREATE');
            }}
          >
            Create
          </a>
        </li>
        {contextControl}
      </ul>
    </div>
  );
}

export default App;

참고

https://opentutorials.org/course/4900/31270

 

수정 기능 구현 - 생활코딩

강의소개 수정 기능을 구현하는 방법을 소개합니다.  강의 소스코드 변경점 import {useState} from 'react'; function Article(props){ return {props.title} {props.body} } function Header(props){ return { event.preventDefault(); prop

opentutorials.org