以下是最常见的生命周期示例:
组件安装
将空数组作为第二个参数传递给useEffect()
,以便仅在装载时运行回调.
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, []); // Pass an empty array to run only callback on mount only.
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
componentDidUpdate
(loose)
通过将单个参数传递到useEffect
,它将在每次渲染后运行.这是一个松散的类似功能,因为这里有一个细微的区别,componentDidUpdate
不会在第一次渲染后运行,但是这个钩子版本会在每次渲染后运行.
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}); // No second argument, so run after every render.
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
componentDidUpdate
(strict)
本例与上述示例的不同之处在于,这里的回调不会在初始渲染时运行,严格模拟componentDidUpdate
的语义.这answer is by Tholle美元,全归功于他.
function Example() {
const [count, setCount] = useState(0);
const firstUpdate = useRef(true);
useLayoutEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log('componentDidUpdate');
});
return (
<div>
<p>componentDidUpdate: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
组件将卸载
在useEffect
的callback参数中返回一个回调,它将在卸载之前被调用.
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// Return a callback in useEffect and it will be called before unmounting.
return () => {
console.log('组件将卸载!');
};
}, []);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
应该更新组件吗
您已经可以使用React.PureComponent
或React.memo
在组件级别实现这一点.为了防止子组件重新招标,此示例取自React docs:
function Parent({ a, b }) {
// Only re-rendered if `a` changes:
const child1 = useMemo(() => <Child1 a={a} />, [a]);
// Only re-rendered if `b` changes:
const child2 = useMemo(() => <Child2 b={b} />, [b]);
return (
<>
{child1}
{child2}
</>
)
}
getDerivedStateFromProps
再一次,从React docs人中摘取
function ScrollView({row}) {
let [isScrollingDown, setIsScrollingDown] = useState(false);
let [prevRow, setPrevRow] = useState(null);
if (row !== prevRow) {
// Row changed since last render. Update isScrollingDown.
setIsScrollingDown(prevRow !== null && row > prevRow);
setPrevRow(row);
}
return `Scrolling down: ${isScrollingDown}`;
}
更新前获取快照
目前还没有类似的钩子.
组件捕获
目前还没有类似的钩子.