将代码从使用 .bind(this) 转换为箭头函数

Converting code from using .bind(this) to arrow functions

我最近被告知在render函数中使用bind(this)是不好的,因为它每次都会创建全新的函数。因此,我正在转向使用箭头函数,如下面的两个 <button> 元素所示。

我的问题是关于地图函数的。它还使用 .bind(this)。有没有办法将其转换为 ES6/7 格式?

return (
    <div>
        <button onClick={()=>this.changeDisplayType("images")}>Images</button>
        <button onClick={()=>this.changeDisplayType("audio")}>Audio</button>
        {
            resources.map(function(resource) {
                return (
                    <div key={resource.id}>
                        <div style={{fontWeight: "bold"}}>{resource.name}</div>
                        <div>({resource.info})</div>
                    </div>
                )
            }.bind(this))
        }


    </div>
)

我也刚刚意识到我可以完全删除 .bind(this) 而我的代码仍然有效。因此,我也想知道它是否存在有什么不同。

Is there a way to convert this to an ES6/7 format?

是的,你可以这样写 arrow function:

resources.map(resource => {
    return (
        <div key={resource.id}>
            <div style={{fontWeight: "bold"}}>{resource.name}</div>
            <div>({resource.info})</div>
        </div>
    )
})

I can remove the .bind(this) completely and my code still works WHY?

因为您没有在地图主体中使用 this 关键字,这意味着如果您尝试访问任何 class 属性 或未绑定回调方法的方法,它将抛出错误。

试试这个:删除绑定并尝试访问地图主体内的状态值,它会抛出错误。