React Class 组件中 Props 和 State 的深度对比
🏷️ 对比表
特性 | Props | State |
---|---|---|
数据来源 | 父组件传递 | 组件内部创建和管理 |
可变性 | 不可变(只读) | 可变(通过 setState 更新) |
作用范围 | 跨组件传递数据 | 组件内部状态管理 |
更新触发 | 父组件重新渲染 | 调用 setState 方法 |
初始化 | 通过父组件的属性传递 | 在 constructor 中初始化 |
类型检查 | 常用 PropTypes 或 TypeScript | 通常由组件内部控制 |
默认值 | 通过 defaultProps 设置 | 直接在 constructor 设置 |
🌟 解析
1. Props(属性)
Props 是组件的输入数据,从父组件流向子组件。
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// 父组件使用
<Welcome name="Alice" age={30} />
特点:
- 是只读的,组件不能修改自己的 props
- 用于组件间通信
- 可以是任何 JavaScript 值(对象、数组、函数等)
2. State(状态)
State 是组件的内部状态,完全由组件自己控制。
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
特点:
- 通过
setState()
方法更新 - 更新会触发组件重新渲染
- 是组件私有的,其他组件无法直接访问
🛠️ 应用场景
何时使用 Props?
- 从父组件向子组件传递数据
- 配置组件的初始状态或行为
- 传递回调函数到子组件
何时使用 State?
- 存储用户输入或表单数据
- 跟踪组件内部的交互状态(如加载状态)
- 管理UI渲染的临时数据
⚠️ 常见误区与解决方案
1. 直接修改 State
// 错误 ❌
this.state.count = 1;
// 正确 ✅
this.setState({ count: 1 });
2. Props 派生 State 的问题
// 反模式 ❌
constructor(props) {
super(props);
this.state = { color: props.color }; // 当props.color变化时不会更新
}
// 解决方案 ✅
static getDerivedStateFromProps(props, state) {
if (props.color !== state.prevColor) {
return {
color: props.color,
prevColor: props.color
};
}
return null;
}
3. 异步更新的 State
// 错误 ❌ - 可能基于过时的state
this.setState({ count: this.state.count + 1 });
// 正确 ✅ - 使用函数形式
this.setState((prevState) => ({
count: prevState.count + 1
}));
🔄 数据流对比
Props 数据流
父组件 → 子组件 → 孙子组件
(单向数据流)
State 数据流
组件内部维护 → 影响自身渲染
(闭环管理)