es-lint 在这种情况下失败: Return 语句不应包含赋值 no-return-assign
我已经研究过这个线程但无济于事:Arrow function should not return assignment 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
)
);
关于javascript - ReactJS es-lint : Return statement should not contain assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63499248/