(精华2020年5月27日更新) react基础篇 react-hooks的useReducer的使用

import React , {useReducer} from 'react'
// (state,action)=>newState
const UseReducer = ()=>{
    const reducer = (state,action) =>{
        if(action.type === 'add'){
            return {
                ...state,
                count:state.count+1
            }
        }else{
            return state
        }
    }
    const addCount = ()=>{
        // dispatch
        dispatch(
            {
                type:'add'
            }
        )
    }
    // 第一项是当前的状态值 第二项是发送action的dispatch函数
    const [state,dispatch] = useReducer(reducer,{count:0})
    return (
        <div>
            <p>{state.count}</p>
            <button onClick={addCount}>增加</button>
        </div>
    )
}

export default UseReducer
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页