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} />
);
}
}
You can also use state in React function components (without a constructor), but using higher-order components or render prop components.
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.
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.
No, you don't need to.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With