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

标签 javascript reactjs ecmascript-6 eslint

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

<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,所以通常我会在构造函数中创建对绑定(bind) func 的引用,但这有所不同,因为每次调用时它都是不同的函数 map 。

最佳答案

其他答案(使用 =>)可能不正确。来自 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}
/>

在 child 中:

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

关于javascript - 上下文映射函数中的 jsx-no-bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41110382/

相关文章:

ecmascript-6 - 仅向 Node 添加 ES2015 模块支持

javascript - webpack 如何在项目目录之外的文件上运行 babel-loader?

javascript - Google Maps v3 - 删除多边形上的顶点

javascript - 如何使用 lodash 从数组中删除值?

javascript - 我什么时候应该在 knockout 中使用括号

jquery - ReactJS 的 setState 与选择下拉菜单混淆

javascript - 如何链接原生 Javascript Promise?

javascript - 如何使时间函数自行更新?

javascript - ReactJS dropzone 通过 webdriver 上传文件

reactjs - 如何删除 Create React App 中的死代码