useReducer的使用

在 hooks 中提供了的 useReducer 功能,可以增强 ReducerDemo 函数提供类似 Redux 的功能,引入 useReducer 后,useReducer 接受一个 reducer 函数作为参数,reducer 接受两个参数一个是 state 另一个是 action 。然后返回一个状态 count 和 dispath,count 是返回状态中的值,而 dispatch 是一个可以发布事件来更新 state 的。

  1. 引入
import React, {
    
     useReducer } from 'react'

在 useReducer 传入 reducer 函数根据 action 来更新 state,如果 action 为 add 正增加 state 也就是增加 count。

全部代码

import React, {
    
     useReducer } from 'react'
// eslint-disable-next-line no-unused-vars
export default function Reducer() {
    
    
  const [count, dispathch] = useReducer((state, action) => {
    
    
    switch(action) {
    
    
      case 'add':
        return state + 1
      case 'sub':
         return state - 1
      default:
         return state
    }
  }, 0)
  return (
    <div>
      <div>{
    
     count }</div>
      <button onClick={
    
    () => {
    
    dispathch('add')}}>+1</button>
      <button onClick={
    
    () => {
    
    dispathch('sub')}}>-1</button>
    </div>
  )
}

猜你喜欢

转载自blog.csdn.net/weixin_45664217/article/details/123218947
今日推荐