티스토리 뷰

habits라는 배열에서 받아온 habit이라는 인자와 id가 같으면 count를 내려주는 로직을 짜고 싶은데

handleDecrement = (habit) => {
    const habits = this.state.habits.map((item) => {
      if (item.id === habit.id) {
        const count = habit.count - 1;
        return { ...habit, count: count < 0 ? 0 : count };
      }
    });
    this.setState({ habits });
  };

이렇게 쓰면 에러가 남

Array.prototype.map() expects a value to be returned at the end of arrow function

map()은 화살표 함수의 끝에 리턴되는 값을 기다린다


handleDecrement = (habit) => {
    const habits = this.state.habits.map((item) => {
      if (item.id === habit.id) {
        const count = habit.count - 1;
        return { ...habit, count: count < 0 ? 0 : count };
      }
      return item; // 조건문이 실행되지 않았을 때를 위한 return도 적어줄 것
    });
    this.setState({ habits });
  };

if 조건문 안에만 생각하고 return을 적어주지 않아서 그랬음!!!!

map()을 사용할 때 return을 꼭 적어주기

 

 

참고

https://stackoverflow.com/questions/45014094/how-do-i-fix-expected-to-return-a-value-at-the-end-of-arrow-function-warning

 

How do I fix "Expected to return a value at the end of arrow function" warning?

Everything works fine, but I have this warning Expected to return a value at the end of arrow function array-callback-return. I tried using forEach instead of map, but then <CommentItem /> do...

stackoverflow.com

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함