一段代码说明 useReducer

一个简单的 useReducer 用法
更新于: 2023-07-17 09:52:31
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;