项目作者: miZyind

项目描述 :
React Hooks (Immer + Reducer + Context)
高级语言: TypeScript
项目地址: git://github.com/miZyind/react-hirc.git
创建时间: 2019-06-25T05:10:29Z
项目社区:https://github.com/miZyind/react-hirc

开源协议:MIT License

下载


react-hirc

NodeJS
NPM
Yarn
TypeScript
React
Prettier
ESLint

React Hooks (Immer + Reducer + Context)

💠 Requirement

  • NodeJS >= 14
  • Yarn ~= 1.22

Installation

  1. yarn add react-hirc

Usage

context/ui.ts

  1. // Node module
  2. import { createAction, createContext } from 'react-hirc';
  3. enum DisplayTypes {
  4. // > 1200
  5. LARGE_MONITOR = 'large monitor',
  6. // 992 ~ 1200
  7. SMALL_MONITOR = 'small monitor',
  8. // 768 ~ 991
  9. TABLET = 'tablet',
  10. // < 768
  11. MOBILE = 'mobile',
  12. }
  13. interface IState {
  14. displayType: DisplayTypes;
  15. }
  16. const initialState: IState = {
  17. displayType: DisplayTypes.LARGE_MONITOR,
  18. };
  19. enum ActionTypes {
  20. WINDOW_RESIZE = '[ui] window resize',
  21. }
  22. const actionCreators = {
  23. windowResize: (width: number) =>
  24. createAction(ActionTypes.WINDOW_RESIZE, width),
  25. };
  26. const { ContextProvider, useContext } = createContext(
  27. initialState,
  28. actionCreators,
  29. (draft, action) => {
  30. switch (action.type) {
  31. case ActionTypes.WINDOW_RESIZE:
  32. const { payload: width } = action;
  33. if (width > 1200) {
  34. draft.displayType = DisplayTypes.LARGE_MONITOR;
  35. }
  36. if (width >= 992 && width <= 1200) {
  37. draft.displayType = DisplayTypes.SMALL_MONITOR;
  38. }
  39. if (width >= 768 && width <= 991) {
  40. draft.displayType = DisplayTypes.TABLET;
  41. }
  42. if (width < 768) {
  43. draft.displayType = DisplayTypes.MOBILE;
  44. }
  45. break;
  46. }
  47. },
  48. );
  49. export { ContextProvider as UIContextProvider, useContext as useUIContext };

pages/_app.tsx

  1. // Node module
  2. import React from 'react';
  3. import App, { Container } from 'next/app';
  4. // Context
  5. import { UIContextProvider } from '../contexts/ui';
  6. export default class MyApp extends App {
  7. render() {
  8. const { Component, pageProps } = this.props;
  9. return (
  10. <Container>
  11. <UIContextProvider>
  12. <Component {...pageProps} ></Component>
  13. </UIContextProvider>
  14. </Container>
  15. );
  16. }
  17. }

pages/index.tsx

  1. // Node module
  2. import React, { useEffect } from 'react';
  3. // Context
  4. import { useUIContext } from '../contexts/ui';
  5. const Index: React.FC = () => {
  6. const {
  7. state: { displayType },
  8. actions: { windowResize },
  9. } = useUIContext();
  10. useEffect(() => {
  11. const handleResize = () => windowResize(innerWidth);
  12. window.addEventListener('resize', handleResize);
  13. return () => window.removeEventListener('resize', handleResize);
  14. }, []);
  15. return (<h1>DisplayType: {displayType}</h1>);
  16. };
  17. export default Index;

Author

miZyind mizyind@gmail.com

LICENSE

Licensed under the MIT License.