我在渲染函数中有以下代码:
<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/