這章要講的是useReducer,他是useState進階的語法,專門來處理複雜邏輯。
import React, {useReducer} from 'react'
function reducer(state, action) {
switch (action.type) {
case 'noadd':
return {count: state.count - 1};
case 'add':
return {count: state.count + 1};
default:
throw new Error();
}
}
export default function Counter() {
const [state, opnum] = useReducer(reducer, {count: 0});
return (
<>
Count: {state.count}
<button onClick={() => opnum({type: 'noadd'})}>-</button>
<button onClick={() => opnum({type: 'add'})}>+</button>
</>
);
}
如上方範例
另外補充
return (
<>
....
</>
);
這樣輸出一樣不會顯示最外層
import React, {useReducer} from 'react'
const oldcount = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'noadd':
return {count: state.count - 1};
case 'add':
return {count: state.count + 1};
case 'rere':
return oldcount;
default:
throw new Error();
}
}
export default function Counter() {
const [state, opnum] = useReducer(reducer, oldcount);
return (
<>
Count: {state.count}
<button onClick={() => opnum({type: 'noadd'})}>-</button>
<button onClick={() => opnum({type: 'add'})}>+</button>
<button onClick={() => opnum({type: 'rere'})}>reset</button>
</>
);
}