问题描述
在React的官方文档中提到 -
In the official docs of React it mentions -
我的问题是 - 我们如何使用 componentWillMount()
钩子中的生命周期方法?
My question is - how can we use the componentWillMount()
lifecyle method in a hook?
推荐答案
你不能使用钩子中的任何现有生命周期方法(componentDidMount,componentDidUpdate,componentWillUnmount等)。它们只能在类组件中使用。而Hooks只能用于功能组件。来自React doc的以下行
You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook.They can only be used in a class components. And Hooks you can only use in a functional components. What the below line from the React doc
建议,您可以在功能组件中模拟类组件的生命周期方法。
suggest is, you can mimic these lifecycle method from class component in a functional components.
componentDidMount 中的代码在安装组件时运行一次。与此行为等效的useEffect挂钩是
Code inside componentDidMount run once when the component is mounted. useEffect hook equivalent for this behaviour is
useEffect(() => {
// Your code here
}, []);
注意这里的第二个参数(空数组)。这只会运行一次。
Notice the second parameter here (empty array). This will run only once.
如果没有第二个参数,将在组件的每个渲染上调用useEffect钩子,这可能是危险的。
Without the second parameter the useEffect hook will be called on every render of the component which can be dangerous.
useEffect(() => {
// Your code here
});
componentWillUnmount用于清理(如删除事件列表器,取消计时器等)。假设您要在componentDidMount中添加一个事件列表器,并在componentWillUnmount中将其重新整理,如下所示。
componentWillUnmount is use for cleanup (like removing event listners, cancel the timer etc). Say you are adding a event listner in componentDidMount and remvoing it in componentWillUnmount as below.
componentDidMount() {
window.addEventListener('mousemove', () => {})
}
componentWillUnmount() {
window.removeEventListener('mousemove', () => {})
}
以上代码的钩子等价如下
Hook equivalent of above code will be as follows
useEffect(() => {
window.addEventListener('mousemove', () => {});
// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
这篇关于如何在React Hooks中使用componentWillMount()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!