生活随笔
收集整理的這篇文章主要介紹了
3 useReducer及其实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import { useState
} from "react"
function reducer(state
, action
) {console.log('reducer接收參數', state
, action
)const { type } = action
switch (type) {case 'add':return { num
: state
.num
+ 1 }case 'minus':return { num
: state
.num
- 1 }}
}
function useReducer(reducer
, initState
) {const [state
, setState
] = useState(initState
)const dispatch = (action
) => {const newVal
= reducer(state
, action
)setState(newVal
)}return [state
, dispatch
]
}
export default function App() {const [state
, dispatch
] = useReducer(reducer
, { num
: 0 })return (<><p
>數:
{state
.num
}</p
><button onClick
={() => dispatch({ type: 'add' })}>+1</button
><br
/><button onClick
={() => dispatch({ type: 'minus' })}>-1</button
></>)
}
總結
以上是生活随笔為你收集整理的3 useReducer及其实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。