react如何设置状态
使用 useState Hook 设置状态
在函数组件中,可以通过 useState Hook 来声明和更新状态。useState 返回一个数组,包含当前状态值和更新状态的函数。
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
使用类组件设置状态
在类组件中,可以通过 this.state 和 this.setState 来管理状态。状态是一个对象,通过 setState 方法更新。

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
状态更新是异步的
无论是 useState 还是 setState,状态更新都是异步的。如果需要基于之前的状态更新,可以使用函数式更新。

// 函数组件
setCount(prevCount => prevCount + 1);
// 类组件
this.setState(prevState => ({
count: prevState.count + 1
}));
合并状态更新
在类组件中,setState 会自动合并状态对象。而在函数组件中,useState 不会自动合并对象状态,需要手动处理。
// 类组件
this.setState({ name: 'John' }); // 保留其他状态
// 函数组件
const [state, setState] = useState({ name: '', age: 0 });
setState(prevState => ({ ...prevState, name: 'John' }));
使用 useReducer 管理复杂状态
对于复杂的状态逻辑,可以使用 useReducer Hook。它类似于 Redux 的 reducer,适合处理包含多个子值的状态对象。
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
}






