React组件中为何需用this而非类名访问状态?
App (Class Name) Instead of this to Access React Component State Great question! This is a super common point of confusion when first diving into React class components—let’s break down exactly why App.state won’t work, and why this.state is the right approach.
1. state is an instance property, not a static class property
When you write state = { ... } inside your App class, you’re using ES6 class instance property syntax. This means every individual instance of the App component gets its own unique copy of state—the state is tied to the specific component instance rendered in your app, not the App class itself.
The App class doesn’t have a built-in static state property. If you try to access App.state directly, you’ll get undefined (and a runtime error when you try to access App.state.persons), because that property simply doesn’t exist on the class.
2. Component reusability depends on instance-specific state
A core idea in React is that components are reusable. Imagine you wanted to render two <App /> components on the same page. If you used App.state to access state, both instances would share the exact same state object—changing state in one would instantly break the other, which is almost never what you want.
Using this.state ensures each component instance manages its own independent state. Each <App /> gets its own state copy, so they can behave separately without interfering with one another.
3. Let’s test your code example
In your code, this line will throw an error immediately:
<Person name={App.state.persons[0].name} age={this.state.persons[0].age} />
Because App.state doesn’t exist at all. The next line using this.state.persons[1].name works because this refers to the current, live instance of the App component—which does have its own state property.
Quick side note on static properties (if you’re curious)
If you explicitly defined a static property on the App class like this:
class App extends Component { static state = { /* some fixed, shared data */ }; // ... rest of your code }
You could access App.state, but this is not how React component state is meant to be used. Static properties are shared across all instances, so they can’t hold dynamic, instance-specific state that changes over time (which is the whole purpose of React’s state system).
内容的提问来源于stack exchange,提问作者Ryder Thacker

