react 的内置状态管理依赖于 usestate 和 usereducer 钩子来管理组件内的状态。详细介绍如下:
usestate:
const [count, setcount] = usestate(0); // update state setcount(count + 1);
使用reducer:
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: return state; } } const [state, dispatch] = useReducer(reducer, initialState); // Dispatch actions dispatch({ type: 'increment' });
这些钩子有助于在组件内本地管理状态,而不需要外部库。