부모컴포넌트로 데이터 보내기(state 끌어올리기)

N·2022년 6월 14일
0
  1. 부모 컴포넌트에 (끌어올린)데이터를 받을 state를 만든다
const [tweets, setTweets] = useState(...생략);
  1. 부모 컴포넌트에 state 변경 함수를 만든다
const addNewTweet = (newTweet) => {
    setTweets([...tweets, newTweet]);
  }; // 이 함수(addNewTweet)가 자식 컴포넌트에 의해 실행되어야 한다
  1. 자식 컴포넌트로 부모 컴포넌트state 변경 함수를 보낸다
return
<div>
	<NewTweetForm 보내는 함수={addNewTweet}/>
</div>
  1. 자식 컴포넌트에서 해당 함수를 받는다
function NewTweetForm({ 보내는 함수 }) {
...생략
}
  1. 자식 컴포넌트에서 부모로 보내고 싶은 데이터를 state로 만든다
const [newTweetContent, setNewTweetContent] = useState("");
  1. state를 변경할 수 있는 함수를 만든다
const onTextChange = (e) => {
    setNewTweetContent(e.target.value);
  };

7-1) 부모 컴포넌트에서 받아온 함수(=보내는 함수)를 호출하는 함수를 만든다.

const onClickSubmit = () => {

   보내는 함수() //부모 컴포넌트의 함수 호출
  };
  

7-2) 변경된 데이터가 반영된 state를 '새로운 변수(newTweet)'에 담는다

const onClickSubmit = () => {
    let newTweet = {  
      uuid: Math.floor(Math.random() * 10000),
      writer: currentUser,
      date: new Date().toISOString().substring(0, 10),
      content: newTweetContent
    };
   
   보내는 함수() //부모 컴포넌트의 함수 호출
  };
  

7-3) 함수로 '새로운 변수(newTweet)'를 전달한다

const onClickSubmit = () => {
    let newTweet = {  
      uuid: Math.floor(Math.random() * 10000),
      writer: currentUser,
      date: new Date().toISOString().substring(0, 10),
      content: newTweetContent
    };
    
   보내는 함수(newTweet) 
   //부모 컴포넌트의 함수 호출
   //newTweet를 addNewTweet(부모컴포넌트)에 전달
  };
  
  1. 자식 컴포넌트에서 함수를 호출하는 버튼 만들기
<button id="submit-new-tweet" onClick={onClickSubmit}>
          버튼
</button>
  1. 버튼을 클릭할 때마다 newTweetContent(변경된 데이터)가 포함된 newTweet이라는 변수(데이터)가 '보내는 함수'로 전달된다.

  2. 부모 컴포넌트에서의 데이터 흐름
    addNewTweet(newTweet) -> setTweets([...tweets, newTweet])

profile
web

0개의 댓글