1. 基本语法
1.1 直接更新状态
class Counter extends React.Component {
state = {
count: 0
};
handleClick = () => {
this.setState({ count: 1 });
};
}
1.2 基于之前的状态更新
class Counter extends React.Component {
state = {
count: 0
};
increment = () => {
this.setState(prevState => ({
count: prevState.count + 1
}));
};
}
2. setState 的特性
2.1 异步更新
class Example extends React.Component {
state = {
count: 0
};
handleClick = () => {
this.setState({ count: this.state.count + 1 });
console.log(this.state.count);
this.setState({ count: this.state.count + 1 }, () => {
console.log(this.state.count);
});
};
}
2.2 状态合并
class Example extends React.Component {
state = {
user: {
name: 'John',
age: 25
}
};
updateUser = () => {
this.setState({
user: {
...this.state.user,
age: 26
}
});
};
}
2.3 批量更新
class Counter extends React.Component {
state = {
count: 0
};
handleClick = () => {
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
this.setState(prevState => ({ count: prevState.count + 1 }));
this.setState(prevState => ({ count: prevState.count + 1 }));
this.setState(prevState => ({ count: prevState.count + 1 }));
};
}
3. 常见使用场景
3.1 表单处理
class Form extends React.Component {
state = {
username: '',
email: ''
};
handleChange = (e) => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<form>
<input
name="username"
value={this.state.username}
onChange={this.handleChange}
/>
<input
name="email"
value={this.state.email}
onChange={this.handleChange}
/>
</form>
);
}
}
3.2 异步操作
class UserProfile extends React.Component {
state = {
user: null,
loading: false,
error: null
};
fetchUser = async () => {
this.setState({ loading: true });
try {
const response = await fetch('/api/user');
const user = await response.json();
this.setState({ user, loading: false });
} catch (error) {
this.setState({ error, loading: false });
}
};
}
3.3 复杂状态更新
class TodoList extends React.Component {
state = {
todos: []
};
addTodo = (text) => {
this.setState(prevState => ({
todos: [
...prevState.todos,
{ id: Date.now(), text, completed: false }
]
}));
};
toggleTodo = (id) => {
this.setState(prevState => ({
todos: prevState.todos.map(todo =>
todo.id === id
? { ...todo, completed: !todo.completed }
: todo
)
}));
};
}
4. 性能优化
4.1 避免不必要的更新
class Example extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return this.state.value !== nextState.value;
}
class Example extends React.PureComponent {
}
}
4.2 状态设计优化
state = {
userFirstName: '',
userLastName: '',
userEmail: ''
};
state = {
user: {
firstName: '',
lastName: '',
email: ''
}
};
5. 常见陷阱和解决方案
5.1 异步陷阱
handleClick = () => {
this.setState({ count: this.state.count + 1 });
this.setState({ count: this.state.count + 1 });
};
handleClick = () => {
this.setState(prevState => ({ count: prevState.count + 1 }));
this.setState(prevState => ({ count: prevState.count + 1 }));
};
5.2 对象更新陷阱
handleClick = () => {
this.state.user.name = 'Jane';
this.setState({ user: this.state.user });
};
handleClick = () => {
this.setState({
user: {
...this.state.user,
name: 'Jane'
}
});
};
6. 最佳实践
6.1 状态设计原则
- 保持状态最小化
- 避免冗余状态
- 合理组织状态结构
- 避免深层嵌套
6.2 更新策略
- 优先使用函数式更新
- 合理使用批量更新
- 正确处理异步操作
- 注意性能优化
7. 总结
7.1 核心要点
- setState 是异步的
- 状态更新会被合并
- 使用函数式更新处理依赖之前的状态
- 注意避免常见陷阱
7.2 使用建议
- 合理设计状态结构
- 正确处理异步和批量更新
- 注意性能优化
- 遵循 React 最佳实践