下面是我写的案例代码,可供参考学习:
import React from 'react'
interface Person {
name: string
age: number
}
const initialState: Person = {
name: '张三',
age: 20
}
const reducer = (state: Person, action: { type: string; payload: number }) => {
switch (action.type) {
case 'increase_age':
return {
...state,
age: state.age + action.payload
}
default:
throw Error('invalid action type.')
}
}
const UseReducer: React.FC = () => {
const [state, dispatch] = React.useReducer(reducer, initialState)
const handleClick = () => {
dispatch({
type: 'increase_age',
payload: 1
})
}
return (
<div>
<p>姓名:{state.name}</p>
<p>年龄:{state.age}</p>
<p>
<button onClick={handleClick}>增加年龄</button>
</p>
</div>
)
}
export default UseReducer