箭头功能不应该返回赋值? [英] Arrow function should not return assignment?

查看:175
本文介绍了箭头功能不应该返回赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在应用程序中正常工作,但是我的寄托不喜欢它,并说我不应该返回分配.怎么了?

My code is working correctly in the app however, my eslint isn't liking it and is saying I should not return assignment. What is wrong with this?

<div ref={(el) => this.myCustomEl = el} />

推荐答案

修复:

<div ref={(el) => { this.myCustomEl = el }} />

说明:

您当前的代码等效于:

<div ref={(el) => { return this.myCustomEl = el }} />

您将返回this.myCustomEl = el的结果.在您的代码中,这并不是真正的问题-但是,当您不小心使用赋值(=)而不是比较器(==或===)时,编程中最令人沮丧的错误之一就会发生,例如:

You are returning the result of this.myCustomEl = el. In your code, this is not really a problem -- however, one of the most frustrating bugs in programming occurs when you accidentally use an assignment (=) instead of a comparator (== or ===), for instance:

// This function will always return **true**, surprisingly
function isEqual(a, b) {
  // The warning would be thrown here, because you probably meant to type "a===b". The below function will always return true;
  return a=b;
}

let k=false;
let j=true;

if(isEqual(k,j)){
  // You'll be very, very, very confused as to why this code is reached because you literally just set k to be false and j to be true, so they should be different, right? Right?
  thisWillExecuteUnexpectedly();
}

在上述情况下,编译器警告是有道理的,因为 k = true 的计算结果为true(与 k === true 相对,这可能是您的意思)键入)并导致意外行为.因此,eshint会在您返回分配时发出通知,假定您要返回比较,并让您知道应该小心.

In the above case, the compiler warning makes sense because k=true evaluates to true (as opposed to k===true, which is probably what you meant to type) and causes unintended behavior. Thus, eshint notices when you return an assignment, assumes that you meant to return a comparison, and lets you know that you should be careful.

在您的情况下,您可以通过不返回结果来解决此问题,这可以通过添加括号{}和不包含return语句来完成:

In your case, you can solve this by simply not returning the result, which is done by adding enclosing brackets {} and no return statement:

<div ref={(el) => { this.myCustomEl = el }} />

您也可以像这样调整eshint警告: https://eslint.org/docs/rules/no-return-assign

You can also adjust the eshint warning like so: https://eslint.org/docs/rules/no-return-assign

这篇关于箭头功能不应该返回赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆