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

如何将Redux TodoMVC示例中的React函数组件转为类组件?

把Redux TodoMVC的函数式App组件转为类组件

先给你完整的可运行类组件代码,直接解决你遇到的super()警告问题:

import React from 'react';
import Header from './Header';
import MainSection from './MainSection';

class App extends React.Component {
  // 要是你不需要在constructor里做额外初始化逻辑,完全可以直接省略这个constructor
  // 下面写完整constructor是为了展示正确的super传参方式
  constructor(props) {
    super(props); // 这里必须传递props,不然就会触发你看到的警告,同时this.props也无法正确初始化
  }

  render() {
    const { todos, actions } = this.props; // 从类组件的props中解构出需要的属性
    return (
      <div>
        <Header addTodo={actions.addTodo} />
        <MainSection todos={todos} actions={actions} />
      </div>
    );
  }
}

export default App;

你遇到警告的原因是什么?

那个App(...): When calling super() in App, make sure to pass up the same props that your component's constructor was passed警告,问题出在constructor的写法上:

  • 当你在类组件的constructor里调用super()时,必须把props作为参数传进去。如果不传,React没法在组件初始化阶段正确绑定this.props,不仅会弹警告,后续用this.props时还可能出意外问题。
  • 另外,如果你不需要在constructor里处理state或者绑定方法,完全可以删掉constructor,React会自动帮你处理super(props)的逻辑,代码会更简洁:
// 简洁版:省略constructor
class App extends React.Component {
  render() {
    const { todos, actions } = this.props;
    return (
      <div>
        <Header addTodo={actions.addTodo} />
        <MainSection todos={todos} actions={actions} />
      </div>
    );
  }
}

函数组件和类组件的核心差异

  • 函数组件直接把props作为参数接收,类组件则要通过this.props访问传入的属性。
  • 类组件必须继承React.Component(或者React.PureComponent做浅比较优化),并且通过render()方法返回JSX结构。

按照上面的代码修改后,你的App类组件就能和原来的函数组件完全一样正常工作,同时解决了警告问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:25:22