userContext.js

    1. import { useReducer, createContext } from 'react';
    2. const initState = {
    3. isLogin: false,
    4. user: {
    5. id: 100,
    6. name: 'lucy'
    7. }
    8. }
    9. export const UserContext = createContext();
    10. // action {type: 'LOGIN', payload: true}
    11. const reducer = (state, action) => {
    12. switch(action.type) {
    13. case 'LOGIN':
    14. return {
    15. ...state,
    16. isLogin: action.payload,
    17. }
    18. default:
    19. break;
    20. }
    21. }
    22. export const UserProvider = ({children}) => {
    23. // reducer, initState 初始值
    24. const [state, dispatch] = useReducer(reducer, initState);
    25. return (
    26. <UserContext.Provider value={{state, dispatch}}>
    27. {children}
    28. </UserContext.Provider>
    29. )
    30. }

    组件使用,index.js

    1. import { UserProvider } from '@/context/userContext'
    2. import App from './App'
    3. export default (props) => {
    4. const [state, setState] = useState()
    5. useEffect(() => {}, [])
    6. return (
    7. <UserProvider>
    8. <App {...props}/>
    9. </UserProvider>
    10. )
    11. }

    App.js

    1. import { useContext } from 'react'
    2. import { UserContext } from '@/context/userContext'
    3. function App() {
    4. const {state, dispatch} = useContext(UserContext)
    5. console.log('userContext', state, dispatch)
    6. function onLogin() {
    7. const action = {
    8. type: 'LOGIN',
    9. payload: true
    10. }
    11. dispatch(action)
    12. }
    13. if(!state.isLogin) return (
    14. <Button onClick={onLogin}>登录</Button>
    15. );
    16. return (<div>欢迎,{state.user.name}</div>)
    17. }