简体   繁体   中英

Bind in constructor or fat arrow in class

So i'm wondering if there is a difference between this:

import React, { Component, PropTypes } from 'react';

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page : 1
    };
  }

  nextPage = () => {
    this.setState({ page: this.state.page + 1 });
  }

  previousPage= () => {
    this.setState({ page: this.state.page - 1 });
  }

  render() {
    const { page } = this.state;
    return (
      <div>
        <H1>{page}</H1>
        <Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
      </div>
    );
  }
}

Or

import React, { Component, PropTypes } from 'react';

class Example extends Component {   
    constructor(props) {
         super(props);
         this.nextPage = this.nextPage.bind(this);
         this.previousPage = this.previousPage.bind(this);
         this.state = {
              page: 1
             };
  }

  nextPage() {
    this.setState({ page: this.state.page + 1 });   }

  previousPage() {
    this.setState({ page: this.state.page - 1 });   }

  render() {
    const { page } = this.state;
    return (
      <div>
        <H1>{page}</H1>
        <Button onClickPrevious={this.previousPage} onClickNext={this.nextPage} />}
      </div>
    );   
  }
}

I'm wondering if it's the same in performance this to every function or are there any other benefits?

a bit of further reading( https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.khf30fuaq )

The best place to bind your event handlers is your constructor . This way your event handler has its context bound to the component instance.You can access props and state and call setState or forceUpdate from such bound handler.

Binding with arrow functions have their own advantages as well. Arrow functions always gets the context from where they have been defined. So in fact, this example is equivalent to:

The arrow function syntax is a way of defining function with a syntax like this:

change = (ev) => this.setState({ text: ev.target.value });

It is a more concise way than writing a function(ev) { .... } statement. If you don't provide { and } brackets after the => arrow, such function is a single expression which is returned instantly. So this desugars to something like:

change = function(ev) { return this.setState({ text: ev.target.value }); }.bind(this);

And hence both of .bind() and arrow function cause a new function to be created

Concluding, the way you want to bind your function depends on your use case.

For more details you can read up this article:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM