What is a Lifecycle Method in React.js? »
If you remember, I told you that there are multiple ways of initializing states in a React component. You’ve already seen one of the ways, which was like this (inside the constructor method):
constructor(props){ super(props); this.state = {hrs: '', hasError: false}; }
There’s an alternate way of doing the same exact thing (to initialize states). You can remove the constructor function altogether and initialize states as follows:
state = {hrs: ’’, hasError: false};
Notice that there’s no this.state here, only state. You use this. accessor only when you’re trying to access an object (which belongs to a class) from a method defined inside that class itself. For instance, this.state was being used because state is an object that belongs to the App class. Now, class App has a method called constructor, inside of which you’re trying to access the object. That’s why you used this. accessor. Now, if you don’t use a constructor, you can use the state object directly. This is how your index.js file should look like after removing the constructor function and defining the states directly inside the component:
import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component { state = {hrs: '', hasError: false}; componentDidMount(){ const getHours = () => { const currentHours = new Date().getHours(); return currentHours; } setTimeout(() => { const hours = getHours().toString(); this.setState({hrs: hours}); }, 3000); } componentDidUpdate(){ console.log("Component got updated on the screen"); } render(){ if (this.state.hasError){ return <div>An error has occurred!</div>; } return <div>Current hour is: {this.state.hrs}</div>; } } ReactDOM.render( <App />, document.querySelector('#root') );
- What is a Lifecycle Method in React.js?
- How to load data using Lifecycle Methods in React.js?
- How to initialize states without constructor in React.js?
- How to pass state as props in React.js?
- How to determine day or night in React.js?
- How to display conditional images in a component in React.js?
- How do compiled code looks like in React.js?
- How to use Config Objects in components in React.js?
- How to show a loading screen when components are loaded in React.js?
- How to specify Default Props in React.js?