其他分享
首页 > 其他分享> > React-Hooks中的useReducer

React-Hooks中的useReducer

作者:互联网

用来践行Flux/Redux的思想

一共分为四步

  1. 创建初始值initialState
  const initial = { 
    n:0
  }
  1. 创建所有操作reducer(state,action)
  const reducer = (state ,action)=>{
     if(action.type === 'add'){
        return{n:state.n+1}//+1操作
     }else if(action.type === 'mult'){
        return{n:state.n*2 }  //*2操作
     }else{
        throw new Error ( 'unknown type' )
      //type错误时报错    
     }
  }
  1. 传给useReducer,得到读和写的API

  2. 调用写API,传入参数({type:'操作类型'})

  function App(){
    const [ state,dispatch ] = useReducer( reducer, initial )
    const {n} = state
    const onClick = ()=>{
    dispatch({type:'add'})
  }
  return(
    <div className='app'>
    <h1>n: {n}</h1>
    <button onClick={onClick}>+1</button>
    </div>
   )
  }

总的来说,useReducer是useState的复杂版


作者:卷毛肥宅
链接:https://juejin.cn/post/6878099754690019335
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

标签:const,Hooks,useReducer,React,state,action,return,type
来源: https://www.cnblogs.com/Free-Thinker/p/15597290.html