Cannot update a component while rendering a different component.

Volc·2022년 8월 17일
0

Error

목록 보기
47/64

Error

다음과 같이 Champion function에 onRemove를 추가했을 때 에러가 발생하였다.

  • CreateChampion.js
  import React,{useState} from 'react';

  function CreateChampion({listId, champions, setChampions}){
      const [inputs, setInputs] = useState({
          name : '',
          skill : ''
      });
      const {name, skill} = inputs;

      const onChange = e => {
          const {name, value} = e.target;
          setInputs({
              ...inputs,
              [name] : value
          })
      }

      const onInsert = () => {
          const Champion = {
              id: listId.current,
              name: name,
              skill: skill
          }
          console.log(Champion)
          setChampions(champions.concat(Champion));
          setInputs({
             name: '',
             skill: ''
          })
          listId.current+=1;
      }

      return(
          <div>
              <input name="name" onChange={onChange} placeholder="챔피언 이름" value={name}/>
              <input name="skill" onChange={onChange} placeholder="스킬" value={skill}/>
              <button onClick={onInsert}>등록</button>
          </div>
      )
  }

  export default CreateChampion;
  • App.js
  import React,{useRef, useState} from 'react';
  import './index.css';
  import CreateChampion from './CreateChampion';

  function Champion({champion, onRemove}){
    return(
      <div>
        <b>{champion.name}</b> <br/>
        <span>스킬: {champion.skill}</span>
        <button onClick={onRemove(champion.id)}>삭제</button>
        <div><br/></div>
      </div>
    )
  }

  function ChampionList({champions, setChampions}) {

    const onRemove = (id) => {
      setChampions(champions.filter( champ => champ.id !== id));
    }

    return (
      <div>
        {champions.map(champion =>(
          <Champion champion={champion} key={champion.id} onRemove={onRemove}/>
        ))}
      </div>
    );
  }

  function App(){
    const listId = useRef(4);

    const [champions, setChampions] = useState(
      [
        {
          id: 1,
          name: '갱플랭크',
          skill: '혀어어어업상'
        },
        {
          id: 2,
          name: '갈리오',
          skill: '단호한 일격'
        },
        {
          id: 3,
          name: '가렌',
          skill: '결정타'
        }
      ]
    )

    return(
      <div>
        <CreateChampion listId={listId} champions={champions} setChampions={setChampions}/>
        <ChampionList champions={champions} setChampions={setChampions}/>
      </div>
    )
  }

  export default App;
  • Error

Error 해결

Champion function에 있는 button을 다음과 같이 바꾸어주었더니 해결되었다.

function Champion({champion, onRemove}){
  return(
    <div>
      <b>{champion.name}</b> <br/>
      <span>스킬: {champion.skill}</span>
      <div><br/></div>
      <button onClick={() => onRemove(champion.id)}>삭제</button>
    </div>
  )
}
profile
미래를 생각하는 개발자

0개의 댓글