美文网首页
useReducer

useReducer

作者: skoll | 来源:发表于2020-06-22 21:18 被阅读0次

简介

1 .类似于redux中的功能,但是这个传值怎么操作

import React,{useState,useEffect,useReducer}from 'react'


// 怎么传值进去呢,全都挂载到action里面
function reducer(state,action){
    switch (action.type){
        case 'add':
            return {count:state.count+action.value};
        case 'sub':
            return {count:state.count-action.value};
        default:
            throw new Error()
    }
}

function App(){
    const [state,dispatch]=useReducer(reducer,{count:0})

    return (
        <>
            点击次数 {state.count}

            <button onClick={()=>dispatch({type:"add",value:10})}>+</button>
            <button onClick={()=>{dispatch({type:"sub",value:1})}}>-</button>
        </>  
    )
}

export default App

相关文章

网友评论

      本文标题:useReducer

      本文链接:https://www.haomeiwen.com/subject/wexexktx.html