一、useReducer 基本用法
const [state, dispatch] = useReducer(reducer, initialArg, init)
- useReducer接收两个参数。第一个参数:reducer 函数。第二个参数:初始化的 state。返回值为最新的state和dispatch函数(用来触发reducer函数,计算对应的state)。
- 按照官方的说法:对于复杂的state操作逻辑,嵌套的state的对象,推荐使用useReducer,所以说useReducer是useState复杂情况下的替代方案。
二、useState和useReducer复杂场景下的使用对比
常规 useState 写法 ```javascript function LoginPage() {
const [name, setName] = useState(''); // 用户名const [pwd, setPwd] = useState(''); // 密码const [isLoading, setIsLoading] = useState(false); // 是否展示loading,发送请求中const [error, setError] = useState(''); // 错误信息const [isLoggedIn, setIsLoggedIn] = useState(false); // 是否登录const login = (event) => {event.preventDefault();setError('');setIsLoading(true);login({ name, pwd }).then(() => {setIsLoggedIn(true);setIsLoading(false);}).catch((error) => {// 登录失败: 显示错误信息、清空输入框用户名、密码、清除loading标识setError(error.message);setName('');setPwd('');setIsLoading(false);});}return (// 返回页面JSX Element)
}
- useReducer写法```javascriptconst initState = {name: '',pwd: '',isLoading: false,error: '',isLoggedIn: false,}function loginReducer(state, action) {switch(action.type) {case 'login':return {...state,isLoading: true,error: '',}case 'success':return {...state,isLoggedIn: true,isLoading: false,}case 'error':return {...state,error: action.payload.error,name: '',pwd: '',isLoading: false,}default:return state;}}function LoginPage() {const [state, dispatch] = useReducer(loginReducer, initState);const { name, pwd, isLoading, error, isLoggedIn } = state;const login = (event) => {event.preventDefault();dispatch({ type: 'login' });login({ name, pwd }).then(() => {dispatch({ type: 'success' });}).catch((error) => {dispatch({type: 'error'payload: { error: error.message }});});}return (// 返回页面JSX Element)}
