相同点
- 它们是react提供的两个用来定义状态的hooks
- 本质来说,
useState
只是预置了reducer
的useReducer
。它们的底层源码中可以看到这一点。
签名
const [state的名字, 用于修改state的函数] = useState(state的初始值)
const [state的名字, 用于修改state的函数] = useReducer((state, action) => 新的state, state的初始值)
useReducer的应用场景
多个状态值
const reducer = (init, action) => {
console.log(init, action)
if (action.type === 'age') {
return { ...init, age: action.payload }
} else if (action.type === 'name') {
return { ...init, name: action.payload }
}
return init
}
const [state, dispatch] = useReducer(reducer, { name: '小花', age: 10 })
// 修改名字
dispatch({ type: 'name', payload: '小花花' })
和useContext一起模拟Redux的功能
思路:定义conText,把dispatch作为公共数据传递给所有的后代。 代码