Reactjs 如何在CreateReact应用程序中添加构造函数?

Reactjs 如何在CreateReact应用程序中添加构造函数?,reactjs,jsx,Reactjs,Jsx,我刚刚开始使用createreact应用程序,对src的设置不是很熟悉。我注意到在App.js中,导出的App组件是一个函数,而不是类App extends React.component 我似乎无法向它添加构造函数。有人知道我在哪里可以这样做吗?谢谢只需在函数中使用useffect 比如: 您可以将函数更改为类,如下所示: import ReactDOM from 'react-dom'; import React, { Component } from 'react'; class Ap

我刚刚开始使用createreact应用程序,对src的设置不是很熟悉。我注意到在App.js中,导出的App组件是一个函数,而不是类App extends React.component


我似乎无法向它添加构造函数。有人知道我在哪里可以这样做吗?谢谢

只需在函数中使用
useffect

比如:


您可以将函数更改为类,如下所示:


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


从“react dom”导入react dom;
从“React”导入React,{Component};
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
文本:“App.js”
}
}
render(){
返回(
{this.state.text}
)
}
}
导出默认应用程序

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 (


但我建议您学习react hooks以保持技能的更新。

因为应用程序是一个功能组件,它没有组件生命周期。因此,不能指定构造函数

但是对于基于类的组件,您可以使用构造函数

class App extends React.Component {
 constructor(props) {
    super(props);

 }

 render(){
 return(
 // code
 //code
 )}
}

功能组件没有
构造函数
,只有基于类的组件才能在其中定义
构造函数
。与构造函数不同的是,这样编写的
useffect
钩子将在每个渲染周期后运行。此钩子不能用作
构造函数
。但解决方案是提供一个类似于构造函数的备用路径@Yousaf在功能组件中这可能是最接近的解决方案,类似于类中的构造函数。不,它不能用作构造函数。它将在与构造函数完全不同或相似的每个渲染周期后运行。@如果您可以使用
useffect
钩子作为构造函数,但必须将第二个参数作为空数组传递
[]
,则在组件装载时它将只运行一次。例如:
useffect(()=警报('once'),[])
@Pablo不正确。当您在
useffect
hook中将空数组作为第二个参数传递时,您模拟的是
componentDidMount
生命周期方法,而不是
构造函数。构造函数在呈现组件之前执行,而
componentDidMount
在呈现组件之后执行。不能将
useffect
组件用作构造函数,也不需要在功能组件内部使用
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
class App extends React.Component {
 constructor(props) {
    super(props);

 }

 render(){
 return(
 // code
 //code
 )}
}