Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

javascript - Pros and cons of using react's life cycle methods in arrow function format

I'm using the public class field syntax (handler = () => {...}) to define all my React components' event handlers so that I can use this for my components without binding them in the constructor. I'm wondering can I use this syntax to use React life cycle methods as well? Say use componentWillMount in this way: componentWillMount = () => {...}

What are the pros and cons if defining react's life cycle method with arrow functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There shouldn't be a need in component lifecycle methods to implicitly bind this (ie: use arrow functions). They are always called from the context of the component, so access to props, state, getState, etc are already available.

So there are no advantages to this pattern. Some disadvantages I can think of are:

  1. More verbose syntax that is still just an ECMAScript proposal.
  2. Confusing to other collaborators. If you are binding this on a component method, I immediately expect that is going to be called by some other entity downstream, ie: click event handlers passed from parent to child.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...