网站搜索

javascript - ReactJS es-lint:return 语句不应包含赋值


es-lint 在这种情况下失败:return 语句不应包含赋值 no-return-assign

我已经查看了这个讨论串,但无济于事:箭头函数不应该返回赋值 no-return-assign

我在这里可以做什么来满足 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

我的猜测是它把 += 1 看作赋值(碰巧这也是状态变更)。

你可能只需在当前状态上加一就能应付。这可能会将你的数组转换为对象,因此请小心使用。

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

通常,对于这样的状态更新,最好是将现有状态映射到下一个状态并更新元素。看起来 incidentMonth 只是一个数组索引,所以你可以通过索引匹配事件。这保证了状态仍然是一个数组。

setMonthlyIncidents((prevIncidents) =>
  prevIncidents.map((incident, index) =>
    incident + index === incidentMonth ? 1 : 0
  )
);

答案#2

尝试

setMonthlyIncidents( { ...前事件,[incidentMonth]: 前事件[incidentMonth] + 1,

}).

你只需要在返回状态时不要赋值。另外,我真的不明白为什么你要创建一个全新的函数来设置状态?(setStateVariable 钩子是做什么的?)。你也可以为那一行禁用 es-lint。