react如何变更state状态
变更 React 状态的常用方法
使用 useState Hook(函数组件)
通过 useState Hook 定义状态变量和更新函数。直接调用更新函数并传入新值即可变更状态:
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
使用 setState 方法(类组件)
在类组件中,通过 this.setState() 更新状态。可以传入新对象或函数(依赖旧状态时更安全):
class Example extends React.Component {
state = { count: 0 };
handleClick = () => {
this.setState({ count: this.state.count + 1 });
// 或使用函数形式
this.setState(prevState => ({
count: prevState.count + 1
}));
};
render() {
return (
<button onClick={this.handleClick}>
Count: {this.state.count}
</button>
);
}
}
状态更新注意事项
- 不可变性:直接修改状态对象无效(如
this.state.count++),必须通过setState或 Hook 更新函数。 - 异步性:状态更新可能是异步的,连续多次更新时应使用函数形式(如
prevState => newState)。 - 合并更新:
setState会浅合并对象,但 Hook 更新函数需手动合并(如setState(prev => ({ ...prev, key: value })))。
复杂状态管理
对于嵌套对象或数组,需创建新引用以确保触发重新渲染:
const [user, setUser] = useState({ name: 'Alice', age: 25 });
// 正确做法:展开旧状态
setUser(prev => ({ ...prev, age: 26 }));
// 数组更新示例
const [items, setItems] = useState(['a', 'b']);
setItems(prev => [...prev, 'c']); // 添加元素
使用 useReducer 管理复杂状态
适用于多个子状态或复杂逻辑的场景:
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<button onClick={() => dispatch({ type: 'increment' })}>
Count: {state.count}
</button>
);
}






