1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import React, { useReducer } from "react"; import Child from "./Child"; import { MyContext } from "./context-manager";
const initState = { step: 0, number: 0, count: 0, };
const reducer = (state, action) => { switch (action.type) { case "stepInc": return { ...state, step: state.step + 1, }; case "numberInc": return { ...state, number: state.number + 1, }; case "count": return { ...state, count: state.step + state.number, }; default: return state; } };
export default function App() { const [state, dispatch] = useReducer(reducer, initState); console.log( `render App step=${state.step}, number=${state.number}, count=${state.count}` );
return ( <MyContext.Provider value={{ state, dispatch }}> <button onClick={() => { dispatch({ type: "stepInc" }); }} > parent step ++ </button> <Child /> </MyContext.Provider> ); }
|