componentDidUpdate和useEffect Hook在没有依赖数组的情况下的行为差异
如果你对React有基本的了解,包括基于类的组件和使用hooks的函数组件,那么你就知道我们可以通过useEffect() hook的依赖数组和返回函数来实现一些类组件的生命周期方法。就像componentDidUpdate方法一样,我们可以通过useEffect来实现,而没有依赖数组。但是你知道吗,在它们访问作用域中的状态方面存在一些差异吗?让我们看看这个差异并理解它:
先决条件:
- 基本的Javascript知识
- ReactJs(基于类的组件和使用hooks的函数组件)
componentDidUpdate: 这是一个仅在基于类的组件中使用的生命周期方法。它会在每次组件更新时立即调用。
语法:
componentDidUpdate(prevProps, prevState, snapshot)
设置应用程序: 按照以下步骤设置应用程序:
步骤1: 使用以下命令创建一个React应用程序:
npx create-react-app foldername
步骤2: 在创建项目文件夹,即文件夹名称之后,使用以下命令进入该文件夹:
cd foldername
项目结构: 项目结构应该如下所示:
示例: 演示componentDidUpdate()的工作原理。在 App.js 文件中写下以下代码:
import { Component } from "react";
// Create App as class based component so we can
// use componentDidUpdate lifeCycle Method
class App extends Component {
constructor() {
super();
this.state = { count: 0 };
}
componentDidUpdate() {
// We will log count in console after every
// update with 500 ms waiting period
setTimeout(() => { console.log(this.state.count) }, 500)
}
render() {
return (
<>
<h1>Count {this.state.count}</h1>
<button onClick={() => this.setState((state) =>
{ return { count: state.count + 1 } })}>
Increment
</button>
</>
);
}
}
export default App;
运行应用的步骤:
从项目的根目录使用以下命令运行应用:
npm start
输出: 现在打开你的浏览器,前往 http://localhost:3000 /,你将看到以下输出:
useEffect(cb,[]):
示例: 为了演示 useEffectHook 的工作原理,请在 App.js 文件中写入以下代码。
import { useEffect, useState } from "react";
const App = () => {
// useState for using state in functional Component
const [count, setCount] = useState(0);
// useEffect with no dependency Array so it
// will triggered on every update of this component
useEffect(() => {
// print count in the console after every
// update with 500 ms waiting time
setTimeout(() => {
console.log(count);
}, 500);
});
return (
<>
<h1>Count {count}</h1>
<button onClick={() =>
setCount((prevCount) => prevCount + 1)}>
Increment
</button>
</>
);
};
export default App;
运行应用程序的步骤: 使用以下命令从项目的根目录运行应用程序:
npm start
输出: 现在打开你的浏览器并访问 http://localhost:3000/,你将看到以下输出:
在上面的示例中,我们在之前的基于类的组件中做了相同的事情。我们在每次更新后打印计数,但这次我们使用了useEffect Hook,因为我们正在实现函数组件。
如果我们再次像点击4次“增量”按钮那样做同样的事情,这次我们得到的结果是1 2 3 4. 为什么??
解释: 所以当计数状态更新时,useEffect将调用并在队列中注册它们的回调函数,但这次回调函数不引用最新的计数状态,因为 在useEffect Hook的回调函数中自行声明了自己的作用域 所以当事件循环执行这些回调时,代码将打印1 2 3 4.