【问题标题】:How do I add Constructor in create-react-app?如何在 create-react-app 中添加构造函数?
【发布时间】:2020-01-01 12:58:11
【问题描述】:

我刚刚开始使用 create-react-app 并且对 src 设置不是很熟悉。我注意到在 App.js 中,导出的 App 组件是一个函数,而不是类 App extends React.Component...

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

【问题讨论】:

  • 功能组件没有constructor,只有基于类的组件可以定义constructor

标签: reactjs jsx


【解决方案1】:

您可以将函数更改为类:


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

【讨论】:

    【解决方案2】:

    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() {
    

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

    【讨论】:

      【解决方案3】:

      由于 App 是一个功能组件,它没有组件生命周期。因此不能指定构造函数。

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

      class App extends React.Component {
       constructor(props) {
          super(props);
      
       }
      
       render(){
       return(
       // code
       //code
       )}
      }
      

      【讨论】:

        【解决方案4】:

        只需在函数中使用useEffect

        喜欢:

        React.useEffect(() => {
            // Whatever you like
            console.log("Called in starting of function");
          }, []);
        

        【讨论】:

        • 与构造函数不同,useEffect 这样编写的钩子将在每个渲染周期后运行。这个钩子不能用作constructor
        • 但解决方案是提供一个替代路径,可以类似于构造函数。 @Yousaf 在功能组件中,这可能是类似于类中的构造函数的最接近的解决方案。
        • 不行,它不能用作构造函数。它将在每个渲染周期后运行,这与构造函数完全不同或相似。
        • @Yousaf 您可以使用useEffect 挂钩作为构造函数,但您必须将第二个参数作为空数组[] 传递,然后它只会在组件挂载时运行一次。例如:useEffect(() = alert('once'), [])
        • @Pablo 不正确。当您在useEffect 挂钩中将空数组作为第二个参数传递时,您将模拟componentDidMount 生命周期方法,而不是constructor。构造函数在组件渲染之前执行,而componentDidMount 在组件渲染之后执行。您不能将useEffect 组件用作构造函数,也不需要在功能组件内部
        猜你喜欢
        • 2018-06-12
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 2021-11-25
        • 1970-01-01
        • 2017-08-04
        • 2016-07-15
        相关资源
        最近更新 更多