[프론트 프로젝트]React에서 컴포트&데이터 구조 생각해 보기

Kyle_Kim·2023년 2월 19일
0

리엑트에서 동일 레벨에 있는 컴포넌트에 데이터를 넘겨 줄 수는 없다. [단방향]

위 글에서는 DiaryEditor과 DiaryList는 트리 내에서 같은 레벨에 있다.

데이터를 위에서 아래로 보낼 수 있다.

App component에서 DiaryList 컴포넌트로.

그러므로 상위 컴포넌트에서 State로 데이터를 관리하며 하위에 있는 동일한 레벨간에 데이터를 전송 할 수 있게 도와줄 수 있게 해줘야 한다.

  • 양뱡향 설정.

실제 프로젝트에 적용

setState(setter)를 DiaryEditor컴포넌트에 Prop으로 전달해 Editor에서 작성한 데이터를 App에 있는 배열에 저장한다.

App.js

const onCreate = (author, content, emotion) => {
    const created_date = new Date().getTime();
    const newItem = {
      author,
      content,
      emotion,
      created_date,
      id: dataId.current,
    };
    dataId.current += 1;
    setData([newItem , ...data]); 
  }
  
        <DiaryEditor onCreate = {onCreate} />

DiaryEditor.js

const DiaryEditor = ({onCreate}) =>{
const authorInput = useRef();
    const contentInput = useRef();
    const [state, setState] = useState({ // setState들을 하나로 묶는다
        author:"",
        content:"",
        emotion: 1,
    });
    const  handleChangeState = (e) =>{
        setState({
            ...state,
            [e.target.name]: e.target.value,
        })
    }
    const handleSubmit = () => {
		---- 중략 ----
        onCreate(state.author, state.content , state.emotion);
        alert("저장성공");
        setState({ //저장 후 데이터 모두 삭제.
            author: "",
            content: "",
            emotion: 1,
        });
    }
	    ---- 중략 ----
}
profile
Make Things Right

0개의 댓글