(精华)2020年7月29日 React react-hooks的useReducer的使用

47 阅读1分钟
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