import { useReducer } from 'react';
// 1. 定义reducer函数 根据不同的action 返回不同的状态
function reducer(state, action) {
switch (action.type) {
case 'INC':
return {...state, count: state.count + 1};
case 'DEC':
return {...state, count: state.count - 1};
case 'SET':
return {...state, count: state.count + action.payload.count}
default:
return state;
}
}
const initialState = {
count: 0
}
function Layout() {
const [state, dispatch] = useReducer(reducer, initialState);
const handleINC = () => {
dispatch({ type: 'INC' });
}
const handleDEC = () => {
dispatch({ type: 'DEC' });
}
const handleSet = () => {
dispatch({ type: 'SET', payload: {count: 100} });
}
return (
<div>
<div>{state.count}</div>
<button onClick={handleINC}>按钮+</button>
<button onClick={handleDEC}>按钮-</button>
<button onClick={handleSet}>点击数值直接加100</button>
</div>
)
}
export default Layout;
hooks useReducer基础用法
于 2023-03-03 14:01:51 首次发布