import React, { createContext, useReducer, useContext, Fragment } from 'react'; import './App.css'; const authReducer = (state, action) => { switch (action.type) { case 'increment': return { ...state, age: state.age + 1 }; case 'login': const { name } = action; return { ...state, name, }; default: return state; } } const AuthContext = createContext(null); const AuthProvider = ({ children }) => { const [state, dispatch] = useReducer(authReducer, { name: 'yang', age: 11, }); return ( {children} ) } const NameLabel = (props) => { const { state, dispatch } = useContext(AuthContext); return ( {state.name} @ {state.age} {props.label} dispatch({ type: 'increment' })}> increment dispatch({ type: 'login', name: Math.random().toString(16) })}> chang name ) } function App() { return ( ); } export default App;
{state.name} @ {state.age}
{props.label}