react中如何使用useReducer?
import React,{useReducer} from 'react';
// redux必须的内容
// store reducer
/*
useReducer使用?
1.创建 数据仓库store 和 管理者reducer
2.通过useReducer(reducer,store)来state和dispatch
*/
const store = {
num:10
}
const reducer=(state,action) =>{
switch (action.type) {
case 'changeNum':
return {
...state,
num:action.num
}
default:
return {
...state
};
}
}
export function Reducer(){
const [state,dispatch] = useReducer(reducer,store);
return(
<div onClick={()=> dispatch({
type:'changeNum',
num:100
})}>
这是一个函数式组件---{state.num}
</div>
)
}