React-Hooks中的useReducer(Usereducer in react hooks)

用来践行Flux/Redux的思想

一共分为四步

  • 创建初始值initialState
  const initial = { 
    n:0
  }
  • 创建所有操作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错误时报错    
     }
  }
  • 传给useReducer,得到读和写的API
  • 调用写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的复杂版

————————

用来践行Flux/Redux的思想

< strong > there are four steps < / strong >:

  • 创建初始值initialState
  const initial = { 
    n:0
  }
  • 创建所有操作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错误时报错    
     }
  }
  • 传给useReducer,得到读和写的API
  • Call the write API and pass in the parameter ({type: ‘operation 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>
   )
  }

< strong > in general, usereducer is a complex version of usestate < / strong >