我刚刚开始使用create-react-app,对src设置不是很熟悉。我注意到在App.js中,导出的App组件是一个函数,而不是App类扩展了React.Component ...
我似乎无法为其添加构造函数。有人知道我在哪里可以做吗?谢谢
您可以将函数更改为类,如下:
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
CRA团队将设置更新为新的React挂钩。您正在谈论旧的反应设置。您可以将其转换
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
收件人
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
但是我建议您学习反应钩子,以保持技能更新。
由于App是功能组件,因此它没有组件生命周期。因此,您不能指定构造函数。
但是使用基于类的组件,您可以使用构造函数
class App extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
// code
//code
)}
}
仅在函数内使用useEffect
。
赞:
React.useEffect(() => {
// Whatever you like
console.log("Called in starting of function");
}, []);