Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react without constructor declaring state in class's body

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} />
    );
  }
}
like image 639
Casa Lim Avatar asked Jan 10 '18 03:01

Casa Lim


People also ask

Can we define state without constructor in React?

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

How do you set a state without a constructor?

The question to answer: How to set initial state in React without a constructor? In this case, there is an initial state for the toggle property in the App component. By using an alternative class syntax, you can leave out the constructor and initialize the state as class field declaration.

Do you need a constructor in React class?

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted.

Is constructor mandatory in class component?

No, you don't need to.


1 Answers

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

like image 179
Hazerd Avatar answered Oct 27 '22 08:10

Hazerd