[英]“Unexpected labeled statement” warnings with Create React App
How would I go about fixing this block of Firebase-related code, to conform to CRA's ESLint rules: 我将如何修复与Firebase相关的代码块,以符合CRA的ESLint规则:
db.broadcasts.on('child_added', (snap) => {
this.setState((prevState) => {
broadcasts: prevState.broadcasts.push(snap)
});
});
Here are the related errors: 以下是相关错误:
I've tried allowing loops : 我试过允许循环 :
/*eslint no-labels: ["error", { "allowLoop": true }]*/
But that gave me the following error: 但这给了我以下错误:
error Unexpected labeled statement
Thanks 谢谢
This rule found a bug in your code. 此规则在您的代码中发现了一个错误。
Rather than work around the rule, you need to fix the bug. 您需要修复错误,而不是解决规则问题。
This part is parsed as a labeled statement: 此部分被解析为带标签的语句:
this.setState((prevState) => {
broadcasts: prevState.broadcasts.push(snap)
});
So the browser sees this: 所以浏览器看到了这个:
this.setState(function(prevState) {
broadcasts: // A label, like in switch() statement
prevState.broadcasts.push(snap);
// This function doesn't return anything
});
There are two issues here: 这里有两个问题:
1) Do not mutate prevState
. 1) 不要改变
prevState
。 This is not how React state works. 这不是React状态的工作方式。 You need to return the next state rather than mutate it in place.
您需要返回下一个状态而不是将其变异。
2) You are not using the ES6 arrow function correctly. 2)您没有正确使用ES6箭头功能。 If you want to implicitly return object, you must put it in parens.
如果要隐式返回对象,则必须将其放入parens中。 Otherwise the browser parses it as a labeled statement.
否则,浏览器会将其解析为带标签的语句。 This is why you get a confusing message about labels.
这就是您收到有关标签的令人困惑的消息的原因。
So, the correct version would look like this: 所以,正确的版本看起来像这样:
this.setState((prevState) => ({ // Note this paren! It is essential.
broadcasts: prevState.broadcasts.concat([snap]) // Note lack of mutation!
}));
Learn more about why immutability is important and about returning object literals from arrow functions . 详细了解为什么不变性很重要以及从箭头函数返回对象文字 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.