node.js - React 箭头函数适用于所有组件方法

标签 node.js reactjs ecmascript-6

箭头函数通常用于需要绑定(bind)来处理事件的方法。

在文档和示例中,生命周期方法(rendercomponentWillMountconstructor...)都被定义为常规函数,这最终会在组件内产生混合方法声明样式。

对所有组件方法使用箭头函数是否安全?

我知道它对于简单的情况来说效果很好,我正在寻找所有潜在的缺点。

最佳答案

是的,如果您想保持一致性,使用箭头函数是安全的。

componentDidMount(){
  console.log(this)
}

返回:

App {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}
context: {}
props: {}
refs: {}
state: null
updater:{isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber:FiberNode {tag: 2, key: null, type: ƒ, stateNode: App, return: FiberNode, …}
_reactInternalInstance:{_processChildContext: ƒ}
isMounted:(...)
replaceState:(...)
__proto__:Component

componentDidMount = () => {
  console.log(this)
}

返回:

App {props: {…}, context: {…}, refs: {…}, updater: {…}, componentDidMount: ƒ, …}
componentDidMount:ƒ ()
context:{}
props:{}
refs:{}
state:null
updater:{isMounted: ƒ, enqueueSetState: ƒ, enqueueReplaceState: ƒ, enqueueForceUpdate: ƒ}
_reactInternalFiber:FiberNode {tag: 2, key: null, type: ƒ, stateNode: App, return: FiberNode, …}
_reactInternalInstance:{_processChildContext: ƒ}
isMounted:(...)
replaceState:(...)
__proto__:Component

这两个方法都记录完全相同的类,除了带有 componentDidMount = () => {} 的类将 componentDidMount 作为属性而不是方法,但仍然以相同的方式调用。

关于node.js - React 箭头函数适用于所有组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066798/

相关文章:

javascript - 在 NODE.js(服务器端)中将 BLOB 文件(音乐文件)转换为 .WAV

javascript - npm run watch 终端错误, "did you forget to signal async completion",有人可以回答吗?

reactjs - Material Table React 上的选择和远程数据分页

javascript - Javascript 中仅返回数组中唯一的对象

javascript - ES6中如何设置单选按钮的selected属性

node.js - 调用 AWS lambda 处理程序回调时遇到 Neptune Gremlin 连接问题

node.js - Heroku NodeJS 部署

javascript - 减少 redux-thunk 样板文件

javascript - React js中的"TypeError: Cannot read property '阻止默认' of undefined"

javascript - Typescript - 检查项目的状况