React-Hooks中的useReducer

311 阅读1分钟

用来践行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的复杂版