上下文映射函数中的 jsx-no-bind

jsx-no-bind in contextual map function

我在渲染函数中有以下代码:

<table className="table table-bordered table-striped">
  <ResultsTableHeader />
  <tbody>
    {results.map(result => (
      <Result
        key={result.get('id')}
        deleteResult={this.props.destroyResult.bind(null, result.get('id'))}
        {...result}
      />
      ))}
  </tbody>
</table>

esling 抱怨 react/jsx-no-bind,所以通常我会在构造函数中创建对绑定 func 的引用,但这是不同的,因为它是来自 map 的每次调用的不同函数。

您可以使用箭头函数语法:

deleteResult={() => this.props.destroyResult(result.get('id'))}

其他答案(使用 =>)可能不正确。 来自 jsx-no-bind 文档:

A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

所以 ESLint 会同时抱怨 bind=>(除非你设置 allowArrowFunctions: true)。

解决方法是将函数调用移到组件内部。

在父级中:

<Result
  key={result.get('id')}
  deleteResult={this.props.destroyResult}
  {...result}
/>

中子:

const Result = (props) => {
  handleDelete = () => props.deleteResult(props.get('id'))
  return (
    <div onClick={handleDelete}></div>
  )
}

为了扩展已经给出的答案,当您将事件分配给处理程序时,它通常会创建一个具有自己范围的函数

deleteResult={this.props.destroyResult.bind(null, result.get('id'))}

当你把赋值写成箭头函数时,你得到了父作用域

deleteResult={() => this.props.destroyResult(result.get('id'))}