useReducer
简单来说就是 useState
进阶用法。而且写法上其实跟 Redux
差异不大。我们就直接来看范例吧
写法如下:
const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
// 第一个参数:事件处理器,第二个参数 state Default Value
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
// state 只能透过 dispatch 方法改变
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
我们刚上面写法中,并没有用到第三个参数,而第三个参数作用就是传入 init function 作为第三个参数。初始的 state 会被设定为 init(initialArg)。
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset'
// 将值回归
return init(action.payload);
default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
<<: [想试试看JavaScript ] 阵列一些操作阵列好用的方法 reduce
>>: 28.unity音乐与音效(AudioSource)
Django + MariaDB + RESTful API + ARC-Day 06 开发 Web...
Virtual Judge ZeroJudge 题意 输入十进位的数字,输出对应的费氏进位表示法 ...
常见的故事 ... 客户 : 系统出错了 , 可以帮忙修一下吗 【・ヘ・?】 工程师 : 我这边看起...
物件导向的设计中,关於建构物件的方式我们成为建构器(constructor),这关系到物件使用的方式...
**Get Ready to Clear Alfresco APSCA Exam by Choosi...