├── public ├── favicon.ico ├── manifest.json └── index.html ├── src ├── App.test.js ├── index.css ├── index.js ├── page │ ├── GlobalContext │ │ ├── index.js │ │ ├── OtherPerson.js │ │ ├── All.js │ │ ├── Person.js │ │ └── utils.js │ ├── index.js │ ├── Home │ │ ├── App.css │ │ ├── logo.svg │ │ └── index.js │ └── Redux │ │ ├── App.css │ │ ├── logo.svg │ │ └── index.js ├── utils.js └── serviceWorker.js ├── .gitignore ├── package.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asyalas/react-hook-demo/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './page'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: http://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/page/GlobalContext/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import All from "./All"; 3 | import OtherPerson from "./OtherPerson"; 4 | import Person from "./Person"; 5 | const Line = () => ( 6 |
13 | ); 14 | const Home = () => { 15 | return ( 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | ); 25 | }; 26 | 27 | export default Home; 28 | -------------------------------------------------------------------------------- /src/page/GlobalContext/OtherPerson.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { createGlobalContext, useContext } from "./utils"; 3 | const OtherPerson = () => { 4 | const OtherPersonStore = createGlobalContext("otherPerson", { 5 | age: 19, 6 | name: "nick" 7 | }); 8 | return ( 9 | 10 | 11 | 12 | ); 13 | }; 14 | const OtherPersonPage = () => { 15 | const { age, name } = useContext("otherPerson"); 16 | return ( 17 |
18 |
姓名:{name}
19 |
年龄:{age}
20 |
21 | ); 22 | }; 23 | 24 | export default OtherPerson; 25 | -------------------------------------------------------------------------------- /src/page/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Router, Switch, Route } from "react-router-dom"; 3 | import Home from "./Home"; 4 | import Redux from './Redux' 5 | import GlobalContext from './GlobalContext' 6 | import "antd/dist/antd.min.css"; 7 | 8 | import * as history from "history"; 9 | export default () => { 10 | return ( 11 | 12 | 13 | ; 14 | ; 15 | ; 16 | 17 | 18 | ); 19 | }; 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-hook-demo", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "antd": "^3.15.1", 7 | "react": "^16.8.5", 8 | "react-dom": "^16.8.5", 9 | "react-redux": "^6.0.1", 10 | "react-router-dom": "^5.0.0", 11 | "react-scripts": "2.1.1", 12 | "redux": "^4.0.1" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject" 19 | }, 20 | "eslintConfig": { 21 | "extends": "react-app" 22 | }, 23 | "browserslist": [ 24 | ">0.2%", 25 | "not dead", 26 | "not ie <= 11", 27 | "not op_mini all" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /src/page/GlobalContext/All.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { useContext } from "./utils"; 3 | import { Button } from "antd"; 4 | const All = () => { 5 | const globalStates = useContext.getGlobal(); 6 | const [state, setState] = React.useState(0); 7 | const addAgeHandle = dispatch => { 8 | dispatch(data => ({ 9 | ...data, 10 | age: data.age + 1 11 | })); 12 | setState(state + 1); 13 | }; 14 | const dom = Object.entries(globalStates).map(([, v]) => ( 15 |
16 | name : {v.name}
17 | age:{v.age} 18 |
19 | value:{JSON.stringify(v.getState())} 20 | 21 |
22 | )); 23 | return dom; 24 | }; 25 | 26 | export default All; 27 | -------------------------------------------------------------------------------- /src/page/GlobalContext/Person.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { createGlobalContext, useContext } from "./utils"; 3 | import { Button } from "antd"; 4 | 5 | const Result = () => { 6 | const { age, name } = useContext("person"); 7 | return ( 8 |
9 |
姓名:{name}
10 |
年龄:{age}
11 |
12 | ); 13 | }; 14 | 15 | const AddButton = () => { 16 | const { dispatch } = useContext("person"); 17 | const addAgeHandle = () => { 18 | dispatch(data => ({ 19 | ...data, 20 | age: data.age + 1 21 | })); 22 | }; 23 | return ( 24 | 27 | ); 28 | }; 29 | const Person = () => { 30 | const PersonStore = createGlobalContext("person", { 31 | age: 18, 32 | name: "harry" 33 | }); 34 | return ( 35 | 36 | 37 | 38 | 39 | ); 40 | }; 41 | 42 | export default Person; 43 | -------------------------------------------------------------------------------- /src/page/Home/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | } 9 | 10 | .App-header { 11 | /* background-color: #282c34; */ 12 | min-height: 100vh; 13 | display: flex; 14 | flex-direction: column; 15 | align-items: center; 16 | justify-content: center; 17 | font-size: calc(10px + 2vmin); 18 | color: white; 19 | } 20 | 21 | .App-button{ 22 | width: 60px; 23 | height: 20px; 24 | background-color: #fff; 25 | /* color: #fff; */ 26 | border-radius: 20px; 27 | margin-bottom: 20px; 28 | } 29 | .App-button-group button{ 30 | width: 80px; 31 | height: 20px; 32 | background-color: #fff; 33 | /* color: #fff; */ 34 | border-radius: 20px; 35 | margin-bottom: 20px; 36 | 37 | } 38 | .App-button-group button+button{ 39 | margin-left: 20px 40 | } 41 | .App-link { 42 | /* color: #61dafb; */ 43 | } 44 | 45 | @keyframes App-logo-spin { 46 | from { 47 | transform: rotate(0deg); 48 | } 49 | to { 50 | transform: rotate(360deg); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/page/Redux/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | } 9 | 10 | .App-header { 11 | /* background-color: #282c34; */ 12 | min-height: 100vh; 13 | display: flex; 14 | flex-direction: column; 15 | align-items: center; 16 | justify-content: center; 17 | font-size: calc(10px + 2vmin); 18 | color: white; 19 | } 20 | 21 | .App-button{ 22 | width: 60px; 23 | height: 20px; 24 | background-color: #fff; 25 | /* color: #fff; */ 26 | border-radius: 20px; 27 | margin-bottom: 20px; 28 | } 29 | .App-button-group button{ 30 | width: 80px; 31 | height: 20px; 32 | background-color: #fff; 33 | /* color: #fff; */ 34 | border-radius: 20px; 35 | margin-bottom: 20px; 36 | 37 | } 38 | .App-button-group button+button{ 39 | margin-left: 20px 40 | } 41 | .App-link { 42 | /* color: #61dafb; */ 43 | } 44 | 45 | @keyframes App-logo-spin { 46 | from { 47 | transform: rotate(0deg); 48 | } 49 | to { 50 | transform: rotate(360deg); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/page/GlobalContext/utils.js: -------------------------------------------------------------------------------- 1 | import * as React from "react"; 2 | let globalContext = {}; 3 | export function useContext(namespace) { 4 | const context = globalContext[namespace]; 5 | return { 6 | ...React.useContext(context), 7 | dispatch: context.dispatch, 8 | getState: context.getState 9 | }; 10 | } 11 | useContext.getGlobal = () => 12 | Object.keys(globalContext).reduce((p, key) => { 13 | p[key] = useContext(key); 14 | return p; 15 | }, {}); 16 | export function createGlobalContext(namespace, initialState) { 17 | const Context = React.createContext(initialState); 18 | if (globalContext.namespace) { 19 | throw new Error("the Context has mounted"); 20 | } 21 | globalContext[namespace] = Context; 22 | const NativeProvider = Context.Provider; 23 | Context.Provider = ({ children }) => { 24 | const [state, setState] = React.useState(initialState); 25 | 26 | Context.dispatch = setState; 27 | Context.getState = () => state; 28 | return React.createElement(NativeProvider, { value: state }, children); 29 | }; 30 | 31 | Context.dispatch = Context.read = () => { 32 | throw new Error("ContextIO not mount"); 33 | }; 34 | 35 | return Context; 36 | } 37 | -------------------------------------------------------------------------------- /src/utils.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useRef, useState ,useCallback} from "react"; 2 | 3 | /** 4 | * 生命周期 componentWillUnmount 5 | * @param fn 6 | */ 7 | export const useWillUnmount = fn => 8 | useEffect(() => { 9 | return () => fn && fn(); 10 | }, []); 11 | 12 | /** 13 | * 生命周期 componentDidMount 14 | * @param fn 15 | */ 16 | export const useDidMount = fn => 17 | useEffect(() => { 18 | if (!!fn) { 19 | fn(); 20 | } 21 | }, []); 22 | 23 | /** 24 | * 生命周期 componentDidUpdate 25 | * @param fn 26 | */ 27 | 28 | export const useDidUpdate = fn => { 29 | const mounting = useRef(true); 30 | useEffect(() => { 31 | if (mounting.current) { 32 | mounting.current = false; 33 | } else { 34 | fn(); 35 | } 36 | }); 37 | }; 38 | 39 | /** 40 | * 强制更新 forceUpdate 41 | */ 42 | export const useForceUpdate = () => { 43 | const [, forceUpdate] = useState(0); 44 | return ()=>forceUpdate(Math.random()); 45 | }; 46 | 47 | /** 48 | * input的onchange事件 49 | * @param {*} initial 50 | */ 51 | export const useInputState = (initial) => { 52 | const [value, setValue] = useState(initial); 53 | const onChange =useCallback( (e) => setValue(e.target.value.trim()),[]); 54 | return [value, onChange, setValue]; 55 | }; 56 | 57 | /** 58 | * 获取更新前的值 59 | * @param {*} value 60 | */ 61 | export const usePrevious = value => { 62 | const ref = useRef(); 63 | useEffect(() => { 64 | ref.current = value; 65 | }); 66 | return ref.current; 67 | }; -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/page/Home/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/page/Redux/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 前言 2 | 3 | react作为前端目前很火的框架,拥有者无数的开发者和活跃的社区,但作为开发者在用react开发的时候,你是否遇到过以下的问题: 4 | 5 | - 复用一个有状态的组件太难 6 | 7 | react的核心思想推荐将一个页面拆成一堆独立的,可复用的组件,并且用自上而下的单向数据流的形式将这些组件串联起来。 8 | 9 | 但实践发现很多组件很冗长且带有状态,不好进行拆分,复用困难大 10 | 11 | 于是官方推荐使用HOC 12 | 13 | - 生命周期钩子函数里的逻辑太乱 14 | 15 | 我们希望一个函数只做一件事,但生命周期钩子函数中,其实同时在做多件事情。同时,在某种情景下,我们需要在componentDidMount和componentDidUpdate做同样的事情 16 | 17 | - class 18 | 19 | 我们用class来创建一个组件的时候,最重要的就是给函数绑定this 20 | 21 | ```js 22 | //不管是 23 | this.handleClick = this.handleClick.bind(this) 24 | //还是 25 | const handleClick = ()=>{} 26 | //或者是 27 | 60 | ``` 61 | 62 | - useEffect 63 | 64 | useEffect相当于componentDidMount,componentDidUpdate的集合,而在返回(return)的函数中,相当于componentWillUnmount。 65 | 66 | 我们可以通过在useEffect设置第二个参数来设置监听的值,类型为数组。传入后,只有数组里面的值变化了,才会执行useEffect,从而来提高性能,如何传入一个空数组 ,那么该 effect 只会在组件 mount 和 unmount 时期执行。 67 | 68 | 但和生命周期不一样的是, 69 | 70 | - useEffect中定义的副作用函数的执行不会阻碍浏览器更新视图,也就是说这些函数是异步执行的 71 | - react首次渲染和之后的每次渲染都会调用一遍传给useEffect的函数 72 | - componentWillUnmount只会在组件被销毁前执行一次而已,而useEffect里的函数,每次组件渲染后都会执行一遍 73 | 74 | ```js 75 | useEffect(()=>{ 76 | window.addEventListener('resize',handleResize) 77 | return ()=>{ 78 | window.removeEventListener('resize',handleResize) 79 | } 80 | }) 81 | ``` 82 | 83 | - useContext 84 | 85 | useContext其实是简化了使用createContext的流程,更加优雅 86 | 87 | ```js 88 | ... 89 | const ThemeContext = React.createContext({ 90 | background: '#282c34', 91 | color: '#61dafb' 92 | }); 93 | 94 | ... 95 | const {color,background} = useContext(ThemeContext); 96 | 97 | ... 98 |
99 | 100 | ``` 101 | - useReducer 提供一个简单化的redux 102 | 103 | ```js 104 | 105 | 106 | const initialState = {count: 0}; 107 | 108 | function reducer(state, action) { 109 | switch (action.type) { 110 | case 'reset': 111 | return initialState; 112 | case 'increment': 113 | return {count: state.count + 1}; 114 | case 'decrement': 115 | return {count: state.count - 1}; 116 | default: 117 | return state 118 | } 119 | } 120 | ... 121 | const [state, dispatch] = useReducer(reducer, initialState) 122 | 123 | ... 124 | 125 |

reducer count:{state.count}

126 |
127 | 128 | 129 | 130 |
131 | 132 | ``` 133 | 134 | - useRef 更加优雅的去获取ref对象 135 | 136 | ```js 137 | function useRefHandle(initial){ 138 | let ref = useRef(initial) 139 | let focusHandle = ()=>ref.current.focus(); 140 | return [ref,focusHandle] 141 | } 142 | ... 143 | let [inputEl,focusHandle] = useRefHandle(null); 144 | ... 145 |

146 | useRef: 147 |

148 | ``` 149 | 150 | ## hook的规则 151 | - 只能在顶层调用Hooks。不要在循环,条件或嵌套函数中调用Hook。确保hook按顺序执行 152 | - 仅从React功能组件调用Hooks,或在自定义的hook中调用。不要从常规JavaScript函数中调用Hook。 153 | 154 | ## 自定义hook 155 | 156 | react hook不仅提供了一些常用方法的hook来让组件写的更加优雅,更加复用,还可以构建自己的Hook可以将组件逻辑提取到可重用的函数中,这样粒度更小,甚至可以作为一个粒度最小的状态类来进行复用。 157 | ```js 158 | const useWindowWith = ()=>{ 159 | 160 | const [innerWidth, setInnerWidth] = useState(window.innerWidth); 161 | 162 | const handleResize = () => setInnerWidth(window.innerWidth) 163 | 164 | useEffect(()=>{ 165 | window.addEventListener('resize',handleResize) 166 | return ()=>{ 167 | window.removeEventListener('resize',handleResize) 168 | } 169 | }) 170 | return innerWidth 171 | } 172 | ... 173 | 174 | const App =(props)=> { 175 | const innerWidth = useWindowWith() 176 | return ( 177 |

当前屏幕宽度:{innerWidth}

178 | ) 179 | } 180 | 181 | ``` 182 | 183 | ## 参考 184 | 185 | https://juejin.im/post/5be3ea136fb9a049f9121014 186 | 187 | ## 最后 188 | 请给我一个star 😊 -------------------------------------------------------------------------------- /src/page/Redux/index.js: -------------------------------------------------------------------------------- 1 | import React, { useState as useReactState, useRef, useEffect } from "react"; 2 | import { Modal, Button, Input, Checkbox } from "antd"; 3 | import { createStore, combineReducers } from "redux"; 4 | import { Provider, connect } from "react-redux"; 5 | import { fromJS, is } from "immutable"; 6 | const deepCompare = (obj1, obj2) => is(fromJS(obj1), fromJS(obj2)); 7 | const isChange = (obj1, obj2, tag) => { 8 | const bol = deepCompare(obj1, obj2); 9 | return bol ? ++tag : tag; 10 | }; 11 | const useState = inital => { 12 | const [value, setValue] = useReactState(inital); 13 | const ref = useRef({}); 14 | const tag = isChange(inital, ref.current.inital); 15 | useEffect(() => { 16 | ref.current = { 17 | tag, 18 | inital 19 | }; 20 | }); 21 | useEffect(() => { 22 | setValue(inital); 23 | }, [tag]); 24 | return [value, setValue]; 25 | }; 26 | const CheckboxGroup = Checkbox.Group; 27 | const UI = props => ( 28 |
37 | {props.children} 38 |
39 | ); 40 | //这是redux的原始state 41 | const tiger = { 42 | num: 0, 43 | name: "", 44 | checkBox: [] 45 | }; 46 | 47 | const increase = "increase"; 48 | const init = "init"; 49 | 50 | //这是reducer 51 | const reducer = (state = tiger, action) => { 52 | switch (action.type) { 53 | case increase: 54 | return { 55 | ...state, 56 | ...action.data 57 | }; 58 | case init: 59 | return { 60 | ...state, 61 | ...action.data 62 | }; 63 | default: 64 | return state; 65 | } 66 | }; 67 | 68 | const ReduxView = props => { 69 | const [name, setName] = useState(props.name); 70 | const [value, setvalue] = useState(props.checkBox); 71 | const [visible, setVisible] = useState(false); 72 | const [data, setData] = useState({}); 73 | console.log("render", props); 74 | useEffect(() => { 75 | new Promise((s, r) => { 76 | setTimeout(() => { 77 | s({ 78 | num: 2, 79 | name: "拉下来的数据", 80 | checkBox: [1, 2] 81 | }); 82 | }, 1500); 83 | }).then(res => { 84 | props.dispatch({ 85 | type: init, 86 | data: res 87 | }); 88 | }); 89 | }, []); 90 | const options = [ 91 | { 92 | value: 1, 93 | label: "复选框1" 94 | }, 95 | { 96 | value: 2, 97 | label: "复选框2" 98 | }, 99 | { 100 | value: 3, 101 | label: "复选框3" 102 | } 103 | ]; 104 | 105 | const increaseHandle = () => { 106 | props.dispatch({ 107 | type: increase, 108 | data: { 109 | num: props.num + 1 110 | } 111 | }); 112 | }; 113 | const submit = () => { 114 | console.log({ 115 | name, 116 | value, 117 | num: props.num 118 | }); 119 | }; 120 | const hideModal = () => setVisible(false); 121 | const openModal = data => { 122 | setVisible(true); 123 | setData(data); 124 | }; 125 | return ( 126 |
127 | 128 | setName(e.target.value)} /> 129 | 130 | 131 | 132 | 133 | 134 |
139 | num:{props.num} 140 |
141 | 144 |
145 | 146 | 149 | 152 | 158 | 159 | 160 | 163 | 164 |
165 | ); 166 | }; 167 | const CustomModal = props => { 168 | return ( 169 | 170 |
我的名字是:
171 | 174 | props.setData({ 175 | ...props.data.name, 176 | name: e.target.value 177 | }) 178 | } 179 | /> 180 |
181 | ); 182 | }; 183 | const ReduxWrap = connect(store => { 184 | return store.root; 185 | })(ReduxView); 186 | 187 | //创建store 188 | const store = createStore( 189 | combineReducers({ 190 | root: reducer 191 | }) 192 | ); 193 | 194 | const reduxDemo = () => ( 195 | 196 | 197 | 198 | ); 199 | export default reduxDemo; 200 | -------------------------------------------------------------------------------- /src/page/Home/index.js: -------------------------------------------------------------------------------- 1 | import logo from "./logo.svg"; 2 | import "./App.css"; 3 | import { Input, Button } from "antd"; 4 | import React, { 5 | useState, 6 | useEffect, 7 | useContext, 8 | useReducer, 9 | useRef, 10 | memo 11 | } from "react"; 12 | 13 | import { 14 | useForceUpdate, 15 | useDidUpdate, 16 | useDidMount, 17 | useWillUnmount, 18 | useInputState, 19 | usePrevious 20 | } from "../../utils"; 21 | const { Group } = Button; 22 | 23 | const ThemeContext = React.createContext({ 24 | background: "#282c34", 25 | color: "#61dafb" 26 | }); 27 | 28 | /** 29 | * 监控浏览器变化 30 | * @return {number} innerWidth 返回当前窗口宽度 31 | * **/ 32 | const useWindowWith = () => { 33 | const [innerWidth, setInnerWidth] = useState(window.innerWidth); 34 | 35 | const handleResize = () => setInnerWidth(window.innerWidth); 36 | 37 | useEffect(() => { 38 | window.addEventListener("resize", handleResize); 39 | return () => { 40 | window.removeEventListener("resize", handleResize); 41 | }; 42 | }); 43 | return innerWidth; 44 | }; 45 | 46 | /** 47 | * 计数 48 | * @param {number} initialState 初始值 49 | * @return {number} count 值 50 | * @return {function} setCount 改变值的方法 51 | * */ 52 | const useCount = initialState => { 53 | const [count, setCount] = useState(initialState); 54 | useEffect(() => {}, [count]); 55 | return [count, setCount]; 56 | }; 57 | 58 | /** 59 | * count-reducer 60 | * * */ 61 | 62 | const initialState = { count: 0 }; 63 | 64 | function reducer(state, action) { 65 | switch (action.type) { 66 | case "reset": 67 | return initialState; 68 | case "increment": 69 | return { count: state.count + 1 }; 70 | case "decrement": 71 | return { count: state.count - 1 }; 72 | default: 73 | return state; 74 | } 75 | } 76 | 77 | /** 78 | * 点击获取焦点 79 | * @param {number} initial 初始值 80 | * @return {object} ref 当前的ref对象 81 | * @return {function} focusHandle 使用该ref对象的函数 82 | * */ 83 | function useRefHandle(initial) { 84 | let ref = useRef(initial); 85 | let focusHandle = () => ref.current.focus(); 86 | return [ref, focusHandle]; 87 | } 88 | 89 | const ChildComponent = memo(props => { 90 | console.log("child component render"); 91 | return

我是子组件,父组件传下来的值为:{props.value}

; 92 | }); 93 | const App = props => { 94 | const innerWidth = useWindowWith(); 95 | const [count, setCount] = useCount(0); 96 | const { color, background } = useContext(ThemeContext); 97 | const [state, dispatch] = useReducer(reducer, initialState); 98 | let [inputEl, focusHandle] = useRefHandle(null); 99 | const [value, onChange] = useInputState(undefined); 100 | const preonChange = usePrevious(onChange); 101 | 102 | console.log( 103 | "------- 在更新的时候onChange是否重新生成 start ----------------" 104 | ); 105 | console.log("onChange", onChange === preonChange); 106 | // 结论:在更新的时候onChange都会重新生成,所以需要用到useCallback对其进行memoize 107 | // 可以在utils里面去掉useInputState的useCallback方法去实验 108 | console.log("------- 在更新的时候onChange是否重新生成 end ----------------"); 109 | console.log("render number"); 110 | 111 | useDidUpdate(() => { 112 | console.log("didUpdate"); 113 | }); 114 | useDidMount(() => { 115 | console.log("didMount"); 116 | }); 117 | 118 | useWillUnmount(() => { 119 | console.log("willUnmount"); 120 | }); 121 | 122 | return ( 123 |
124 | {/* useContext demo */} 125 |
126 | logo 127 |

react hook demo

128 | {/* forceUpdate */} 129 | 132 | {/* useState demo */} 133 |

count:{count}

134 | 137 | 138 | {/* useReducer demo */} 139 |

reducer count:{state.count}

140 | 141 | 147 | 153 | 156 | 157 | 158 | {/* useEffect demo */} 159 |

当前屏幕宽度:{innerWidth}

160 | 161 | {/* useRef demo */} 162 |

163 | useRef:{" "} 164 | 165 | 168 |

169 | {/* memo */} 170 | 171 | {/* useContext demo */} 172 | 179 | Learn React 180 | 181 |
182 |
183 | ); 184 | }; 185 | 186 | // export default useHooks(App) 187 | export default App; 188 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------