React-Hooks中的useReducer
用来践行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的复杂版
作者:卷毛肥宅
链接:https://juejin.cn/post/6878099754690019335
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。