函数组件
1 2 3
| const Hello = (props) =>{ return <div>{props.message)}</div> }
|
1
| const Hello = props => <div>{props.message}</div>
|
1 2 3
| function Hello(props){ return <div>{props.message}</div> }
|
useState
1 2 3 4 5 6 7 8 9 10 11 12
| const App = () => { const [n, setN] = useState(0); const onClick = () => { setN(n + 1); }; return ( <div> {n} <button onClick={onClick}>+1</button> </div> ); };
|
模拟 componentDidMount
:
1
| useEffect( ()=> {console.log('第一次渲染')}, [] )
|
模拟 componentDidUpdate
:
1 2 3 4 5 6 7 8 9 10 11
| useEffect( ()=> {console.log('任意属性变更')} ) useEffect( ()=>{console.log('n 变了')}, [n])
useEffect(() => { console.log("state 变了"); });
useEffect(() => { console.log("n 变了"); }, [n]);
|
模拟 componentWillUnmount
:
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
| useEffect( ()=> { console.log('第一次渲染') return ()=>{ console.log('组件要死了') } })
const App = () => { let [childVisible, setChildVisible] = useState(true); const show = () => { setChildVisible(true); }; return ( <div> {childVisible ? ( <button onClick={() => setChildVisible(false)}>hide</button> ) : ( <button onClick={show}>show</button> )} {childVisible ? <Child /> : null} </div> ); }; const Child = (props) => { useEffect(() => { console.log("渲染或变化了"); return () => { console.log("Child 销毁了"); }; }); return <div>Child</div>; };
|
constructor
函数组件执行的时候,就相当于 constructor
shouldComponentUpdate
React.memo
useMemo
render
函数组件的返回值 就是 render 的返回值。
自定义 Hook 之 useUpdate
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
| const useUpdate = (fn, dep) => { const [count, setCount] = useState(0); useEffect(() => { setCount((x) => x + 1); }, [dep]);
useEffect(() => { if (count > 1) { fn(); } }, [count, fn]); };
const App = () => { const [n, setN] = useState(0); const onClick = () => { setN(n + 1); }; useUpdate(() => { console.log("n变了"); }, n);
return ( <div> {n} <button onClick={onClick}>点击+1</button> </div> ); };
|
useRef demo
useContext demo
能用函数组件就用函数组件
因为简单。