You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React与Redux中constructor和super的props传递差异疑问

为什么React类组件要给constructor和super传props,而Redux场景下却不用?

咱们先拆解React里的情况:
在React的类组件中,如果你需要在constructor方法里直接访问this.props,那必须把props同时传给constructor和super。举个例子:

constructor(props){ 
  super(props); 
  this.state = { memeLimit: 10 } 
}

要是你不传props给super,那在constructor里调用this.props会得到undefined——虽然组件其他生命周期方法(比如render)里依然能正常拿到props,但constructor是个例外,因为React要等super执行完,才会把props挂载到组件实例上。当然啦,如果你的constructor里根本不需要用到props,理论上也可以不传,但很多开发者会养成传的习惯,避免后续修改代码时踩坑。

再说说Redux的场景:
你给出的Redux示例代码里,constructor没传props,核心原因是这个组件的constructor里完全不需要访问props。通常用Redux时,我们会通过connect高阶组件把Redux store里的状态和dispatch方法映射成组件的props,但如果你的constructor只是初始化内部状态(比如示例里的memeLimit),完全没用到this.props,那自然不需要把props传给constructor和super。

简单总结:传不传props的关键,从来不是用不用Redux,而是你是否要在组件的constructor方法里访问this.props。

内容的提问来源于stack exchange,提问作者claudiopb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:03:11