申明state变量
state: count ; 初始值: 0 ; 变化方法: setCount
const [count, setCount] = useState(0);
使用副作用函数
// 每次count 发生变化时, 触发对应的副作用函数
useEffect(() => {
console.log(count);
// 调用一个新的 effect 之前对前一个 effect 进行清理
return () => {
console.log('组件已经卸载', count);
};
}, [count]);
- 如果想执行只运行一次的 effect(仅在组件挂载和卸载时执行),可以传递一个空数组([])作为第二个参数
自定义Hook函数
- 必须以use开头
使用 useReducer 管理复杂组件
function useReducer(reducer, initialState) {
const [state, setState] = useState(initialState);
function dispatch(action) {
const nextState = reducer(state, action);
setState(nextState);
}
return [state, dispatch];
}
function Todos() {
const [todos, dispatch] = useReducer(todosReducer, []);
function handleAddClick(text) {
dispatch({ type: 'add', text });
}
// ...
}
- 建议使用
const reducer = (state, action) => ({ ...state, ...action }); - 直接定义
const [state, setState] = useReducer(reducer, { count: 1 }); - 使用
setState进行state的更新
使用 useCallback 和 useMemo
- useCallBack 缓存的是 函数, useMemo 缓存的是 变量
- 把内联回调函数及依赖项数组作为参数传入 useCallback,它将返回该回调函数的 memoized 版本,该回调函数仅在某个依赖项改变时才会更新
useCallback(fn, deps) 相当于 useMemo(() => fn, deps)
使用 useImperativeHandle
- 可以让你在使用 ref 时自定义暴露给父组件的实例值。
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);
Hook 简单使用实例
/* 引入 React 中的 useState Hook。它让我们在函数组件中存储内部 state。 */
1: import React, { useState } from 'react';
2:
3: function Example() {
/*
在 Example 组件内部,我们通过调用 useState Hook 声明了一个新的 state 变量。
它返回一对值给到我们命名的变量上。我们把变量命名为 count,因为它存储的是点击次数。
我们通过传 0 作为 useState 唯一的参数来将其初始化为 0。第二个返回的值本身就是一个函数。
它让我们可以更新 count 的值,所以我们叫它 setCount。
*/
4: const [count, setCount] = useState(0);
5:
6: return (
7: <div>
8: <p>You clicked {count} times</p>
/*
当用户点击按钮后,我们传递一个新的值给 setCount。
React 会重新渲染 Example 组件,并把最新的 count 传给它。
*/
9: <button onClick={() => setCount(count + 1)}>
10: Click me
11: </button>
12: </div>
13: );
14: }