箭头函数通常用于需要绑定(bind)来处理事件的方法。
在文档和示例中,生命周期方法(render
、componentWillMount
、constructor
...)都被定义为常规函数,这最终会在组件内产生混合方法声明样式。
对所有组件方法使用箭头函数是否安全?
我知道它对于简单的情况来说效果很好,我正在寻找所有潜在的缺点。
最佳答案
是的,如果您想保持一致性,使用箭头函数是安全的。
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/