react中如何使用useReducer?
作者:互联网
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>
)
}
标签:reducer,useReducer,dispatch,react,如何,state,num,store 来源: https://www.cnblogs.com/malong1992/p/15367246.html