在 hooks 中提供了的 useReducer 功能,提供类似 Redux 的功能。useReducer接收一个 reducer 函数作为参数,reducer 接收两个参数state 和 action 。
count 是返回状态中的值, dispatch 派发事件来更新 state 。useReducer的第二个参数将count默认值设为0
const [count, dispatch] = useReducer((state, action) => {
// 这里写逻辑
}, 0)
当点击按钮的时候使用dispatch派发事件,用法同redux
完整代码如下:
import React, { useReducer } from 'react'
import { Button } from "antd";
function Demo05() {
const [count, dispatch] = useReducer((state, action) => {
switch (action.type) {
case 'add':
return state + 1
case 'sub':
return state - 1
default:
return state;
}
}, 0)
return (
<div>
<h1>{count}</h1>
<Button onClick={() => dispatch({ type: 'add' })}>点击+1</Button>
<Button onClick={() => dispatch({ type: 'sub' })}>点击-1</Button>
</div>
)
}
export default Demo05