useReducer的作用,就是官网说的那样,它时useState的替代方案,返回当前的state和对应的dispatch。
这里仅仅记录一下使用的方法,大家也可以参考官网:
export 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();
}
}
import React, { useReducer } from "react";
import {reducer} from "../reducer"
const initialState = { count: 0 };
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return <React.Fragment>
Count:{state.count}
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</React.Fragment>
}
|