一段代码说明 useReducer
一个简单的 useReducer 用法
import { useReducer } from "react";
const reducer = (state, action) => {
if (action.type == "add")
return { ...state, count: state.count + action.payload };
return state;
};
const App = () => {
const [state, dispatch] = useReducer(reducer, null, () => {
return { count: 200 };
});
const addcount = () => {
dispatch({ type: "add", payload: 2 });
};
return (
<div>
<h1>{state.count}</h1>
<button onClick={addcount}>+++</button>
</div>
);
};
export default App;