是的,您可以借助useEffect钩子在功能组件中使用生命周期方法。
useEffect 钩子可用于复制生命周期行为。例如:
componentDidMount:
componentDidMount() {
window.addEventListener('unhandledRejection', handler);
}
功能组件等价
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
}, [])
componentWillUnmount:
componentWillUnmount() {
alert('The component is going to be unmounted');
window.removeEventListener('unhandledRejection', handler);
}
功能组件等价
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
alert('The component is going to be unmounted');
window.removeEventListener('unhandledRejection', handler);
}
}, [])
componentDidUpdate:
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
功能组件等价
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array