react 16
中的hooks
在function
组件中可以使用state
和生命周期等class
组件的属性
基础HOOKS
useState
在function
组件中使用state
1 2
| const [state, setState] = useState(initialState); setState(newState);
|
懒初始化state
1 2 3 4
| const [state, setState] = useState(() => { const initialState = someExpensiveComputation(props); return initialState; });
|
useEffect
在function
组件中使用didMount
和didupdate
及willUnmout
生命周期
1 2 3 4 5 6 7 8
| useEffect(() => { const subscription = props.source.subscribe(); return () => { subscription.unsubscribe(); }; }, [props.source]);
|
useContext
1
| const value = useContext(MyContext);
|
接受一个context
对象(数据来自React.createContext
),返回当前context
对象的最新值。当前context
对象指虚拟dom
树中最近<MyContext.Provider>
的值。当最近的<MyContext.Provider>
的上级组件更新时,这个HOOK
也会用当前context
对象的最新值重绘组件。
附加的HOOKS
useReducer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const initialState = {count: 0};
function reducer(state, action) { switch (action.type) { case 'increment': return {count: state.count + 1}; case 'decrement': return {count: state.count - 1}; default: throw new Error(); } }
function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <> Count: {state.count} <button onClick={() => dispatch({type: 'increment'})}>+</button> <button onClick={() => dispatch({type: 'decrement'})}>-</button> </> ); }
|
useCallback
只有当依赖[a, b]
有更新时才会返回一个新的memoizedCallback
,优化子组件的不必要渲染
1 2 3 4 5 6
| const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], );
|
useMemo
只有当依赖[a, b]
有更新时才会返回一个新的memoizedValue
,优化子组件的不必要渲染
1
| const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
|
useRef
获取引用对象
1 2 3 4 5 6 7 8 9 10 11 12 13
| function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
|