React Hooks之useReducer

186 阅读1分钟

useContext函数和useReducer很像,并且合作可以完成类似的Redux库的操作。在开发中使用useReducer可以让代码具有更好的可读性和可维护性,并且会给测试提供方便。

reducer是什么?

reducer其实就是一个函数,这个函数接收两个参数,一个是状态,一个用来控制业务逻辑的判断参数。我们举一个最简单的例子。 function countReducer(state, action) { switch(action.type) { case 'add': return state + 1; case 'sub': return state - 1; default: return state; } } 上面的代码就是Reducer,你主要理解的就是这种形式和两个参数的作用,一个参数是状态,一个参数是如何控制状态。

userReducer的使用

useReducer了,它也是React hooks提供的函数,可以增强我们的Reducer import React, { useReducer } from 'react';

function ReducerCounter(){
    const [ count , dispatch ] = useReducer((state,action)=>{
        switch(action){
            case 'add':
                return state+1
            case 'sub':
                return state-1
            default:
                return state
        }
    },0)
    return (
    <div>
        <h2>现在的分数是{count}</h2>
        <button onClick={()=>dispatch('add')}>Increment</button>
        <button onClick={()=>dispatch('sub')}>Decrement</button>
    </div>
    )

}

export default ReducerCounter

以上就是useReducer的使用,其实也很简单吧,可以在工作中帮你解决很多问题。