我刚刚创建了一个函数组件,其中包含表达式 const [state, setState] = useState()
。现在我可以访问 state
和 setState()
,这个有状态函数组件与有状态类组件非常相似。我只知道这个组件和典型的类组件之间的两个区别:当引用状态时,我们必须使用 state.handle
而不是 this.state.handle
,我们可以在 render
方法之外轻松访问 Context API。
除了我已经发现的差异之外,这个有状态函数组件和有状态类组件之间还有什么区别吗?我的上述说法是否错误?
稍微细化一下这个问题,有什么事情是类组件可以做而带 Hooks 的函数组件做不到的吗?
最佳答案
上钩之前:
- 有状态和无状态之间有明显的区别 组件。
- 当您希望组件具有一些功能时,可以使用编写类 状态,并且当您认为您的 组件不需要任何状态。
后钩:
通过引入 Hooks,我们可以在不使用类的情况下创建有状态组件。
我们可以使用函数来创建有状态组件。
有用的文章
正如 Sung M. Kim 所说,react hooks 中有 3 个生命周期 hooks 尚未实现。
- 从Props获取DerivedState
As mentioned in the docs, getDerivedStateFromProps exists for only one purpose. It enables a component to update its internal state as the result of changes in props.
您可以使用 useEffect 和 useState Hook 实现相同的目的。 useEffect 接受因变量数组作为第二个参数,这将导致 useEffect 重新运行,因此您可以执行以下操作:
const [state1, changeState1] = useState(props.prop1);
useEffect(() => {
changeState1(props.prop1)
}, [props.prop1]);
componentDidCatch
getDerivedStateFromError
此钩子(Hook)捕获子树中的错误,但以下错误 ( docs ) 除外:
Event handlers (learn more) Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) Server side rendering Errors thrown in the error boundary itself (rather than its children)
关于reactjs - react : Difference between a Stateful Class Component and a Function Component using Hooks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57642594/