react中的constructor和super

     经验贴,站在巨人的肩膀上学习,通过查阅资料,结合自己的理解,总结得出规律。
      [1](https://www.cnblogs.com/faith3/p/9219446.html)
      [2](https://www.jianshu.com/p/82966e22a6bd)

1. constructor

我们平常在写react框架是,定义一个类组件,有时候会用到constructor和super,如下图。

export default class App extends Component {
 constructor() {
    super();

     this.state = {
      message: "你好啊"
    }
  }

但很多时候又忽略不写,那这应用在什么场景呢。
查阅资料,直接总结

由ES6的继承规则得知,不管子类写不写constructor,在new实例的过程都会给补上constructor。
所以:constructor钩子函数并不是不可缺少的,子组件可以在一些情况略去。

有constructor钩子函数时候,Child类会多一个constructor方法。可以定义state,如果用户不定义state的话,有无constructor钩子函数时候没有区别。

有constructor钩子函数,定义sate情况

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

               this.state={
                
                   counter:0
               }
              }

              render(){
                  return(
                      <div>
                        <h2>当前计数:{this.state.counter}</h2>
                        <button onClick={this.increment.bind(this)} >+1</button>
                        <button onClick={this.decrement.bind(this)}>-1</button>
                      </div>
                  )
              }

没有constructor钩子函数情况

export default class App extends Component {
  render() {
    return (
      <div>
        <ChildCpn name="why" age="18" height="1.88" />
        <ChildCpn name="kobe" age="40" height="1.98" />
      </div>
    )
  }
}

总结:
如果组件要定义自己的state初始状态的话,需要写在constructor钩子函数中,
如果用户不使用state的话,纯用props接受参数,有没有constructor钩子函数都可以,可以不用constructor钩子函数。

2.super
super就跟java里面的用法类似,子类继承父类,需要通过super继承。不然的话会产生报错。

3. props
我们可以看到钩子函数应有有些是有参数有些是无参数的。

无参数

export default class App extends PureComponent {
  
  render() {
  
    return (
      <div>
        APP:{this.props.name}
      </div>
    )
  }
}

只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props

<think>好的,用户想了解Reactconstructor的用法以及如何用它来初始化状态。首先,我需要回忆React类组件中constructor的作用。根据引用[2][4],constructor在类组件中用于初始化state绑定方法。必须调用super(props),否则this.props会未定义。然后,用户可能想知道具体的步骤注意事项,比如为什么要在constructor里初始化state,以及如何正确使用props来赋值state。 接下来,要确保解释constructor的基本结构,如示例代码中的super(props)this.state的赋值。同时,需要注意在constructor中使用props时,是否需要直接传递,或者是否需要处理props的变化,比如在引用[2]中提到使用props为state赋值时要仔细,可能涉及到派生状态的问题。 另外,用户可能对函数组件如何初始化状态感兴趣,但问题明确提到constructor,所以可能主要集中在类组件。不过可以稍作对比,比如函数组件使用useState来初始化状态,但不在constructor里。不过根据用户的问题,暂时不需要深入函数组件。 还需要提到constructor的其他用途,比如方法绑定,如引用[3]中的状态更新导致重新渲染,可能涉及到事件处理函数的绑定。例如,在constructorthis.handleClick = this.handleClick.bind(this)这样的操作。 然后,注意事项部分需要强调super(props)的必要性,避免直接修改state,以及使用props初始化state时的潜在问题,比如props变化时state不会自动更新,这时候可能需要使用getDerivedStateFromProps,但这是一个高级话题,可能用户暂时不需要,但可以提及。 最后,生成相关问题需要考虑用户可能的后续疑问,比如为什么使用super(props),或者如何避免直接修改state,或者函数组件如何处理状态初始化,以及constructor的其他用途。这时候参考引用中的内容,确保问题覆盖用户可能感兴趣的方面。 总结回答的结构应该是:constructor的作用,基本用法(代码示例),其他用途(方法绑定),注意事项,相关问题。需要引用提供的参考文献来支持每个点,比如引用[2]中的示例代码,引用[3]中的状态更新机制等。</think>### React类组件中constructor的使用方法及初始化状态 #### 一、constructor的核心作用 1. **初始化状态**:`constructor`是类组件中唯一可以直接为`this.state`赋值的地方。例如: ```javascript class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; // ✅ 合法初始化 } } ``` [^2][^4] 2. **方法绑定**:用于绑定事件处理函数的`this`指向(ES6类方法默认不绑定`this`): ```javascript constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); // 🔧 绑定方法 } ``` #### 二、基本语法规范 ```javascript class MyComponent extends React.Component { constructor(props) { super(props); // 🚨 必须调用super(props),否则this.props将未定义 this.state = { loggedIn: false, value: this.props.initialValue // ⚠️ 需谨慎使用props初始化state }; } } ``` #### 三、初始化状态的两种场景 | 场景 | 示例代码 | 注意事项 | |---------------------|----------------------------------|----------------------------| | 直接初始化固定值 | `this.state = { isOpen: false }` | 避免后续直接修改`this.state` | | 基于props派生初始值 | `this.state = { data: props.initialData }` | 父组件props更新时不会自动同步到state | #### 四、注意事项 1. **禁止的行为**: - ❌ 直接修改状态:`this.state.count = 1`(必须用`this.setState()`) - ❌ 省略`super(props)`:会导致`this.props`未定义 - ❌ 在constructor中调用setState():此时组件尚未挂载 2. **函数组件对比**: ```javascript // 函数组件使用useState初始化 function MyFuncComponent() { const [count, setCount] = useState(0); // 🎯 无constructor return <div>{count}</div>; } ``` #### 五、相关引用说明 - 引用[2]详细展示了props初始化state的代码模式 - 引用[3]解释了state更新触发渲染的机制 - 引用[4]对比了类组件与函数组件的初始化差异 §§ 1. 为什么必须在constructor中调用super(props)[^2]? 2. 如何避免使用props初始化state时的潜在问题? 3. 函数组件如何实现类似constructor的功能[^4]? 4. constructor中能否进行异步数据请求?为什么?[^3] 5. 类组件与函数组件在状态管理上的主要区别是什么[^4]?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值