ReactJS es-lint : Return 문은 할당을 포함하지 않아야합니다.

Aug 20 2020

es-lint는이 경우에 실패합니다 : Return 문에는 할당 no-return-assign이 포함되지 않아야 합니다.

이 스레드를 살펴 보았지만 아무 소용이 없습니다 : Arrow 함수는 할당을 반환하지 않아야합니다.

es-lint를 만족시키기 위해 여기서 무엇을 할 수 있습니까?

내 상태 변수

const [monthlyIncidents, setMonthlyIncidents] = useState([
    // monthlyIncidents[0] -> January ... monthlyIncidents[11] -> December
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
  ])

상태를 업데이트하는 방법

setMonthlyIncidents((prevIncidents) => {
   return { ...prevIncidents, [incidentMonth]: monthlyIncidents[incidentMonth] += 1 }
})

답변

1 DrewReese Aug 20 2020 at 13:17

내 생각 엔 += 1as 할당 (우연히도 상태 변형)을 보는 것입니다.

당신은에 의해받을 수 있습니다 단지 현재 상태에 하나를 추가. 이것은 배열을 객체로 변환 할 가능성이 있으므로주의하십시오.

setMonthlyIncidents((prevIncidents) => {
  return {
    ...prevIncidents,
    [incidentMonth]: prevIncidents[incidentMonth] + 1,
  }
})

일반적으로 이와 같은 상태 업데이트의 경우 기존 상태를 다음 상태로 매핑하고 요소를 업데이트하는 것이 좋습니다. incidentMonth단순히 배열 인덱스 처럼 보이 므로 인덱스별로 사건을 일치시킬 수 있습니다. 이렇게하면 상태가 배열로 유지됩니다.

setMonthlyIncidents((prevIncidents) =>
  prevIncidents.map((incident, index) =>
    incident + index === incidentMonth ? 1 : 0
  )
);
1 HaroonAzharKhan Aug 20 2020 at 13:40

시험

setMonthlyIncidents ({... prevIncidents, [incidentMonth] : prevIncidents [incidentMonth] + 1,

}).

상태를 반환하는 동안 상태를 할당 할 필요가 없습니다. 게다가 상태를 설정하기 위해 완전히 새로운 함수를 만드는 이유를 알 수 없습니다. ( setStateVariable훅은 무엇을합니까?). 해당 라인에 대해 es-lint를 비활성화 할 수도 있습니다.