I've just started using create-react-app and am not very familiar with the src setup. I noticed that in App.js, the exported App component is a function, as opposed to class App extends React.Component...
I can't seem to add a constructor to it. Anyone know where I can do so? Thank you
You can change the function to a class as:
import ReactDOM from 'react-dom';
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
text: 'App.js'
}
}
render() {
return (
<div>
{this.state.text}
</div>
)
}
}
export default App
Just use useEffect
within the function.
Like:
React.useEffect(() => {
// Whatever you like
console.log("Called in starting of function");
}, []);
CRA team updated the setup to new React hooks. You are talking about old react setup. You can convert it
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
To
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
But i will suggest you to learn react hooks to keep your skills updated.
As App is a functional component it doesn't have the component lifecycle. Therefore you can't specify a constructor.
But with class Based Component you can use the constructor
class App extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
// code
//code
)}
}
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.