데이터 삭제하기

minho·2022년 2월 22일
0

완성본




삭제버튼을 통해 데이터 리스트를 제거한다.


App.js

function App() {
  const [data, setData] = useState([]);

  const dataId = useRef(0);

  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]); //...data는 원래데이터 + newItem은 새로운 데이터
  }

  const onDelete = (targetId) => {
    console.log(`${targetId}가 삭제되었습니다.`)
    const newDiaryList = data.filter((it) => it.id !== targetId);
    console.log(newDiaryList);
    setData(newDiaryList);    
  };

  return (
    <div>      
      <DiaryEditor onCreate = {onCreate} />
      <DiaryList onDelete ={onDelete} diaryList = {data} />
    </div>
  );
};
  • onDelete()를 만든다.

  • onDelete는 DiaryItem에게 보내줘야 하므로 DiaryList를 통해 보내줘야 한다.
    (DiaryList는 DiaryItem안에 있으므로 DiaryItem통해 보내줘야 한다.)

  • filter를 이용하여 제거할 리스트의 id인 targetId외의 요소들을 리스트로 만든다.

    네번째[3](targetId = 3)목록에서 제거버튼을 누르면 targetId=4이외의 요소들로 리스트가 채워진다.

  • data를 조작할수 있는 setData에 newDiaryList를 넣어주면 위의 목록들이 그대로 들어가므로 제거가 완료된다.


DiaryList

import DiaryItem from './DiaryItem';
const DiaryList = ({ onDelete, diaryList }) => {
    console.log(diaryList);
    return (
        <div className="DiaryList">
            <h2>일기 리스트</h2>
            <h4>{diaryList.length}개의 일기가 있습니다.</h4>
            <div>
                {diaryList.map((it) => (
                    <DiaryItem key = {it.id} {...it} onDelete={onDelete} />
                  //DiaryItem에 onDelete를 전달한다.
                ))}
            </div>
        </div> 
    );   
}

DiaryList.defaultProps = {
    diaryList: [],
};

export default DiaryList;

DiaryItem

const DiaryItem = ({onDelete, author, content, created_date, emotion, id }) => {
    return (
        <div className='DiaryItem'>
            <div className='info'>
                <span>
                    작성자 : {author} | 감정점수 : {emotion}
                </span>
                <br />
                <span className='date'>{new Date(created_date).toLocaleString()}</span>
            </div>
            <div className='content'>{content}</div> 
            <button //삭제하기 버튼
                onClick={() => {                    
                    if(window.confirm(`${id}번째 일기를 삭제하시겠습니까?`)){
                        onDelete(id); //id를 받아서 onDelete의 매개변수로 사용한다.
                    }
                }}
            >
                삭제하기
            </button>   
        </div>
    );
};

export default DiaryItem; 
  • DiaryItem에서는 onDelete()에 매개변수인 id를 넣어주어 실행한다.
profile
Live the way you think

0개의 댓글