6

I saw below code somewhere and I'm curious. It looks cleaned but unusual to me. Why state = {} is declared without an constructor?

and load declared without a function keyword? As I know for there are ways to write a function

function async load() {} or const async load = ()=>{}

And what ...args does? is it spread arguments?

import View from './View';
import loadData from './loadData';
export default class extends Component {
  state = {};
  load = this.load.bind(this);
  async load(...args) {
    try {
      this.setState({ loading: true, error: false });
      const data = await loadData(...args);
      this.setState({ loading: false, data });
    } catch (ex) {
      this.setState({ loading: false, error: true });
    }
  }
  render() {
    return (
      <View {...this.props} {...this.state} onLoad={this.load} />
    );
  }
}
Casa Lim
  • 355
  • 3
  • 5
  • 15
  • Check this https://stackoverflow.com/questions/45832853/initialise-state-as-a-class-property-or-in-constructor-reactjs/45833026#45833026 – Shubham Khatri Jan 10 '18 at 09:39

2 Answers2

2

The state = {} declaration is a class property, which is currently not part of the JavaScript language. Certain utilities such as Babel will compile this into legal JavaScript code.

However, the lack of a function keyword within classes, as well as the ... operator are part of ECMAScript 6, which has been officially implemented into the language (though some browsers do not recognize it yet).

Class Definition
Spread Operator

Hazerd
  • 336
  • 1
  • 7
0

Yes, you can initialize state without a constructor for a React class component:

class Counter extends Component {
  state = { value: 0 };

  handleIncrement = () => {
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
  };

  handleDecrement = () => {
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
  };

  render() {
    return (
      <div>
        {this.state.value}

        <button onClick={this.handleIncrement}>+</button>
        <button onClick={this.handleDecrement}>-</button>
      </div>
    )
  }
}

It uses class field declarations which are not part of the language yet but enabled with Babel. You can checkout a sample application over here.

You can also use state in React function components (without a constructor), but using higher-order components or render prop components. You can find out more about it here.

Robin Wieruch
  • 14,900
  • 10
  • 82
  • 107