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

React组件中为何使用this.setState()而非super.setState()?

Why do we use this.setState() instead of super.setState() in React components?

Great question! As a React beginner, it makes total sense to be curious about this distinction—let's unpack it step by step.

1. Understanding this vs super in class inheritance

When you create a class component like Checkbox that extends React.Component:

  • super refers to the parent class (React.Component) itself, not the instance of your Checkbox component.
  • this refers to the current instance of your Checkbox component—the specific object that's created when your component renders.

React's setState() method is defined in the parent React.Component class, and your Checkbox class inherits this method. When you call this.setState(), you're invoking the inherited method on your component's own instance, which is exactly what you want to update your component's state.

2. Why super.setState() won't work for your component

If you tried to use super.setState(), you'd be trying to update the state of the parent React.Component class's generic instance—not the state of your specific Checkbox component. Each React component instance maintains its own independent state, so modifying the parent class's state has no impact on your component's UI or data.

3. Let's tie this to your example

In your Checkbox component:

class Checkbox extends React.Component {
  constructor(props) {
    super(props)
    this.state = { checked: true }
    this.handleCheck = this.handleCheck.bind(this)
  }

  handleCheck() {
    // This updates the CURRENT Checkbox instance's state
    this.setState({ checked: !this.state.checked })
  }

  render() {
    var msg
    if(this.state.checked) {
      msg = "checked"
    } else {
      msg = "not checked"
    }
    return (
      <div>
        <input type="checkbox" onChange={this.handleCheck} checked={this.state.checked} />
        <p>Checkbox is {msg}</p>
      </div>
    )
  }
}

When handleCheck runs, this.setState() updates the checked value in this specific Checkbox instance's state. The render method then reads this updated state to show the correct message and checkbox state. If you used super.setState() here, nothing would change in your component's UI—because you're not modifying the state that belongs to your component instance.

Quick side note on super(props)

You might notice we call super(props) in the constructor—this is required because it initializes the parent class with your component's props, which allows this to be properly bound to your component instance in the constructor. After that, all method calls (like setState) use this to reference your component's own instance.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:47:49