箭头函数不应该return赋值吗?

Arrow function should not return assignment?

我的代码在应用程序中正常运行,但是我的 eslint 不喜欢它,并说我不应该 return 赋值。这有什么问题吗?

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

你正在隐式地返回一个赋值。 this.myCustomEl = el 是一个赋值。您可以通过将箭头函数更改为 (el) => { this.myCustomEl =el } 来修复此 linting 错误,它不再隐式返回,因为您将它包装在 {} 而不是 ().

旁注:在 render 方法中内联声明一个箭头函数会破坏 PureComponent 因为每次你的组件渲染它都必须声明一个新的匿名函数,所以 PureComponent 所做的浅层道具比较被这个打破了,并且总是会重新渲染。

尝试将其作为组件的方法。

class MyClass extends React.PureComponent {
    getRef = (el) => { this.ref = el; }

    render() {
        return <div ref={this.getRef} />;
    }
}

如果上面的语法不适合你,你可以使用下面的语法:

class MyClass extends React.PureComponent {
    constructor(props) {
        super(props);

        this.ref = null;

        this.getRef = this.getRef.bind(this);
    }

    getRef(el) {
        this.ref = el;
    }

    render() {
        return <div ref={this.getRef} />;
    }
}

修复:

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

解释:

您当前的代码相当于:

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

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

// 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 的计算结果为真(与 k===true 相反,这可能是您要键入的内容)并导致意外行为。因此,当您 return 一个赋值时,eshint 会注意到,假设您打算 return 一个比较,并让您知道您应该小心。

在你的情况下,你可以通过简单地不 returning 结果来解决这个问题,这是通过添加括号 {} 并且没有 return 语句来完成的:

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

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

只是想记下我遇到的一些事情。我安装了 Prettier,它一直带走我的括号,导致 eslint 错误: 为了确认这一点,我添加了一个 prettier-ignore:

    <div>
        {/*prettier-ignore*/}
        <Map
            ref={(m) => {
                this.leafletMap = m;
            }}
            center={mapCenter}
            zoom={zoomLevel}
        >
            <TileLayer
                attribution={stamenTonerAttr}
                url={stamenTonerTiles}
            />
        </Map>
    </div>