• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

공부하다가 하도 해결안되어 질문 남깁니다 ㅠㅠ

20.08.25 22:27 작성 조회수 89

0

안녕하세요 저는 제로초님의 강의를 통해 리액트를 공부하고있는 사람입니다.

혼자 공부하던중 도무지 해결안되는 부분이 있어서 이렇게 질문을 남깁니다.

------------------------------------------------------------------------------------

  const [isChecked, setIsChecked] = useState([]);

  const [amllShopList, setAmllShopList] = useState([]);

const handleAddRow = (e) => {   //추가버튼

    e.preventDefault();

    const newRow = {

      shopNm : '',

      shopTel : '',

      shopAddr : '',

      shopBrn : ''

    }

    setAmllShopList([...amllShopList,newRow]);

  }

  const handleListEdit = (index, name, value) => {     //내용수정

    setAmllShopList(produce(amllShopList,(draft) => {draft[index][name]=value}));

  }

  const handleDelRow = (e) => {   //삭제버튼(체크박스 선택한것들)

    e.preventDefault();

    //if(isEmpty(isChecked)) return showAlert('삭제할 지점을 선택해주세요.');

    // const resData = amllShopList.filter((data,i)=> !isChecked[i]);

    // setAmllShopList(resData);

    setAmllShopList(amllShopList.filter((data,i)=>!isChecked[i]));

    setIsChecked([]);

  }

  const handleCheckRow = (e) => {   //체크박스 선택

    const index = parseInt(e.target.name);

    isChecked[index] = !isChecked[index];

    setIsChecked([...isChecked]);

  };

  <>

            <div>

            <h5 className="mb8 mt40" style={{ display: 'inline-block', verticalAlign: 'top' }}>

            지점 등록

            </h5>

                  <Button size="sml" background="gray" title="추가" width={80} height={40} buttonMarkup={true} onClick={handleAddRow} />

      <Button size="sml" background="gray" title="삭제" width={80} height={40} buttonMarkup={true} onClick={handleDelRow} />

----------렌더링하는부분--------

              {amllShopList.map((row, i) => 

                <AmllShopList key={i} rowNum={i} isChecked={isChecked[i]} onCheckRow={handleCheckRow} onEdit={handleListEdit}/>

            )}

              </tbody>

            </table>

          </>

--------------------------------

---------컴포넌트-----------------------------

export const AmllShopList = ({rowNum, isChecked, onCheckRow, onEdit}) => {

  const handleAmllCheck = (e) => {
    onCheckRow(e);
  };

  const handleInputChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    onEdit(rowNum, name, value);
  };

  return(
    <tr>
      <td><CheckBox id={'chk_row-'+rowNum} name={rowNum} checked={isChecked} onChange={handleAmllCheck}/></td>
      <td><Input type="text" id={'shopNm-' + rowNum} name="shopNm"   onChange={handleInputChange} /></td>
      <td><Input type="text" id={'shopTel-' + rowNum} name="shopTel"   onChange={handleInputChange} /></td>
      <td><Input type="text" id={'shopAddr-' + rowNum} name="shopAddr"  onChange={handleInputChange} /></td>
      <td><Input type="text" id={'shopBrn-' + rowNum} name="shopBrn"   onChange={handleInputChange} /></td>
    </tr>
  )
}

-----------------------------------

원하는 형태는

추가버튼을 통해 amllShopList 배열에 객체 데이터를 추가하여 값을 입력할수있고, 

체크박스를 통해 삭제할수있는 기능을 구현하는것이었으나,

현재 상황은 추가하고 데이터의 입력은 가능하지만 체크박스로 체크하여 삭제를 할경우

실제 상태값은 정상적으로 삭제가 되고있으나, 화면상으로는 가장 마지막 데이터가 지워지는것처럼 보이게 됩니다.

ex) 추가버튼을 5번 눌러 객체를 5개 추가하여 3,4번째 객체를 체크하여 삭제할경우, 화면상으로는 1,2,3번 데이터가 보이게되지만 실제 데이터는 1,2,5번 데이터가 남아있는상태로 api에 들어가게됨.

해결법좀 알려주세요 ㅠㅠ

답변 1

답변을 작성해보세요.

0

지금 데이터 구조가 복잡하기 때문에 체크박스에 체크를 할 때 구조를 바꾸시는 걸 추천드립니다. 기본적으로 빈 배열로 놓으시고 [], 예를 들어 3, 4번 체크를 하신 경우에는 [2, 3] 이렇게 갖고 계시고 4번 취소하면 [2]으로 그 후 5번 클릭하면 [2, 4]로 가게 해놓으세요.

그래서 삭제할 때는 checkbox.filter 돌면서 내 index가 2이나 4가 아닌지 체크해서 아닌것들만 걸러내시면 되겠습니다.