reactjs - 在什么场景下,react生命周期钩子是必须的
问题描述
以下是 react 生命周期 hook 的官方案例。下面这种情况,如果我稍作改动,把setInterval改成setTimeout,放到render()中,这样setTimeout就会setState,然后循环调用render(),循环setTimeout。也可以实现,那么为什么在这种情况下需要使用生命周期钩子,或者有什么好处呢?清理代码?为了减少内存消耗??
官方示例:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
this.setState({
date: new Date()
}), 1000);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
我的修改
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
this.timerID = setTimeout(
this.setState({
date: new Date()
}),1000);
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
解决方案
如果您在函数中创建一个函数(在本例中为间隔)render()
,这将在每个组件渲染中创建,因此在性能方面真的很糟糕,(render
方法将在不到 1 秒内发生)。
componentDidMount
有利于订阅或在组件挂载后做一些事情,也componentWillUnmount
有利于取消订阅。
因此,当您使用间隔时,您希望将其初始化componentDidMount
并清除componentWillUnmount
componentDidMount() {
this.timer = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
推荐阅读
- android - 注意:无法读取 [Ljava.lang.Object;@79d6c4df 的获取 kotlin 元数据
- c# - c#中的多个条件
- python - 激活后 Conda 环境无法正常工作
- php - Xdebug 在 Notepad++(XAMPP 环境)中不显示 PHP 变量
- java - 评论和评论回复表的 Cassandra 结构
- c# - C# MySQL 将相同的数据插入到 2 个不同的表中
- cmake - GTest/GMock 使用 vcpkg 产生链接器错误
- java - ORA-29532: Java 调用被未捕获的 Java 异常终止:java.awt.HeadlessException
- c - 在 C 语言中,字符数组是否总是且仅用于表示字符串?
- python - 一个类重写了我希望不会改变的变量