React에서 Hook을 사용하는 State의 배열 추가/삭제/수정

2020. 12. 3. 18:11서버 프로그래밍

맨날 기억이 안난다. ㅠㅠ

const [joinList, setJoinList] = useState(['Oliver' ,'Harry' ,'George' ,'Noah' ,'Jack' ,'Jacob' ]);

//Add item
const addJoinPeople = (e) =>{
let name = e.target.value;
setJoinList([...joinList, name]);
};

//Delete item
const RemovePeople = (e) =>{
let name = e.target.value;
setJoinList(joinList.filter((e)=>(e !== name)))
};

medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

 

How to Add to an Array in React State using Hooks

The .push() function will not work, but the .concat() function can update React State when state is an array — as can the spread operator.

medium.com

tyindpgood.medium.com/add-delete-item-from-state-array-in-react-hook-9d7f73d66d80

 

Add / delete item from state array in React (hook)

Test data 測試資料

tyindpgood.medium.com

const [datas, setDatas] = useState([
  {
    id: 1,
    name: "john",
    gender: "m",
  },
  {
    id: 2,
    name: "mary",
    gender: "f",
  },
]);

const updateFieldChanged = (name, index) => (event) => {
  let newArr = datas.map((item, i) => {
    if (index == i) {
      return { ...item, [name]: event.target.value };
    } else {
      return item;
    }
  });
  setDatas(newArr);
};

return (
  <React.Fragment>
    {datas.map((data, index) => {
      <li key={data.name}>
        <input
          type="text"
          name="name"
          value={data.name}
          onChange={updateFieldChanged("name", index)}
        />
      </li>;
      <li key={data.gender}>
        <input
          type="text"
          name="gender"
          value={data.gender}
          onChange={updateFieldChanged("gender", index)}
        />
      </li>;
    })}
  </React.Fragment>
);

stackoverflow.com/questions/55987953/how-do-i-update-states-onchange-in-an-array-of-object-in-react-hooks

 

How do I update states onchange in an array of object in React Hooks

I have retrieved datas stored using useState in an array of object, the datas was then outputted into form fields. And now I want to be able to update the fields (state) as I type. I have seem exa...

stackoverflow.com