一、useReducer
作用:和useState的作用类似,用来管理相对复杂的状态数据
使用:
1、定义一个reducer函数(根据不同的action返回不同的新状态)
2、在组件中调用useReducer,并传入reducer函数的状态和初始值
import { useReducer } from "react"
function reducer(state, action) {
switch (action.type) {
case 'add':
return state += 1
case 'DEC':
return state -= 1;
default:
return state
}
}
const Login = () => {
const [state, dispatch] = useReducer(reducer, 0)
return (
<>
<div>{state}</div>
<button onClick={()=>dispatch({type:'add'})}>+</button>
</>
)
}
export default Login
如何更新state?在dispatch中多加一个载荷payload(规范)
import { useReducer } from "react"
function reducer(state, action) {
switch (action.type) {
case 'add':
return state += 1
case 'DEC':
return state -= 1;
case 'update':
return action.payload;
default:
return state
}
}
const Login = () => {
const [state, dispatch] = useReducer(reducer, 0)
return (
<>
<div>{state}</div>
<button onClick={()=>dispatch({type:'add'})}>+</button>
<button onClick={()=>dispatch({type:'update',payload:100})}>update</button>
</>
)
}
export default Login
下一章:useMemo