箭头功能不应该返回赋值?

Ann*_*aSm 23 javascript reactjs eslint

我的代码在应用程序中正常工作,但是,我的eslint不喜欢它,并且说我不应该返回作业.这有什么问题?

<div ref={(el) => this.myCustomEl = el} />
Run Code Online (Sandbox Code Playgroud)

Aid*_*han 42

您当前的代码相当于:

<div ref={(el) => { this.myCustomEl = el }} />
Run Code Online (Sandbox Code Playgroud)

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

<div ref={(el) => { return this.myCustomEl = el }} />
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,编译器警告是有意义的,因为k = true计算结果为true并导致意外行为.因此,eshint会在您返回作业时发出通知,假设您打算返回比较,并告诉您应该小心.

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

let k=false;  
if(k=true){
  thisWillExecute();
}
Run Code Online (Sandbox Code Playgroud)

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


Kyl*_*son 9

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

旁注:在渲染方法中声明内联箭头函数会破坏 a PureComponent,因为每次组件渲染时都必须声明一个新的匿名函数,因此 a 所做的浅层 props 比较会被PureComponent破坏,并且始终会重新渲染。

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

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

    render() {
        return <div ref={this.getRef} />;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果上述语法不适合您,您可以使用以下语法:

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} />;
    }
}
Run Code Online (Sandbox Code Playgroud)