React — useReducer使用方法

1.定义一个reducer函数(根据不同的action返回不同的新状态)

2.在组件中调用useReducer,并传入reducer函数和状态的初始值

3.事件发生时,通过dispatch函数分发一个action对象(通知reducer)要返回哪个新状态并渲染UI

import { useReducer } from "react"

// 1.定义一个reducer函数,根据不同的action 返回不同的状态
function reducer(state,action){
    if(action.type === 'add'){
        return state +=1
    }else if(action.type === 'sub'){
        return state -=1
    }else{
        return state
    }
}
const Board= ()=>{
    // 组件中调用useReducer hook函数  useReducer(reducer,0)=>[state,dispatch]
    const [state,diapatch] = useReducer(reducer,0)
    return <>

        <div>
            {/* 调用dispatch({type:'add'})=>通知reducer产生一个新的状态 并更新视图 */}
            <button onClick={()=>diapatch({type:'sub'})}>-</button>
            <span>{state}</span>
            <button onClick={()=>diapatch({type:'add'})}>+</button>
        </div>
    
    
    </>
}

export default Board

4.分派action时传参

function reducer(state,action){
    if(action.type === 'add'){
        return state +=1
    }else if(action.type === 'sub'){
        return state -=1
    }else if(action.type === 'set'){
        return state = action.payload //action.payload是传过来的参数
    }else{
        return state
    }
}


 <button onClick={()=>diapatch({type:'set',payload :100})}>更新</button>

 

posted on 2024-03-15 13:54  萬事順意  阅读(42)  评论(0编辑  收藏  举报