- Explain lifecycle of ReactJS due to all call to this.setState() function
- Javascript实现
Explain lifecycle of ReactJS due to all call to this.setState() function
React 是一个 UI 库。它呈现用 JSX 编写的组件。您可以根据自己的使用情况构建和渲染任何组件。 React.js 引入了状态的概念。状态用于存储特定组件的数据。可以使用 this.setState 函数相应地更新这些状态。状态的更新导致 UI 的呈现。在这些渲染过程中会调用不同的生命周期方法。
首次加载应用时调用的生命周期方法:
- 构造函数()
- 渲染()
- componentDidMount()
调用 this.setState 时调用的生命周期方法:
- 渲染()
- componentDidUpdate()
方法:让我们创建一个 React 项目,然后我们将创建一个向 this.setState 发送调用的 UI。用户可以与UI交互,点击按钮触发事件通过this调用this.setState。用户可以在控制台视图中查看上面提到的所有生命周期方法。
创建 React 项目:
第 1 步:要创建一个反应应用程序,您需要通过 npx 命令安装反应模块。使用“npx”而不是“npm”,因为您将在应用的生命周期中只需要一次此命令。
npx create-react-app project_name
第 2 步:创建 react 项目后,移入文件夹以执行不同的操作。
cd project_name
项目结构:运行上述步骤中提到的命令后,如果您在编辑器中打开项目,您可以看到类似的项目结构,如下所示。新组件的用户所做的或我们将要执行的代码更改将在源文件夹中完成。
项目结构
示例:我们将创建一个按钮,通过 this.setState 发送更新状态的调用。
- App.js
Javascript实现
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
message: "initial state"
}
console.log("Constructor called");
}
componentDidMount() {
console.log("componentDidMount called");
}
componentDidUpdate() {
console.log("componentDidUpdate called");
}
call() {
this.setState({ message: "state updated" })
}
render() {
console.log("render called");
// Rendering a button
return (
<div style={{ margin: 100 }}>
<button onClick={() => { this.call() }}>
Click to update state!
</button>
<p>{this.state.message}</p>
</div>
);
}
}
export default App;
运行应用程序的步骤:打开终端并键入以下命令。
npm start
输出:打开浏览器。默认情况下,它将打开一个运行 localhost (http://localhost:3000/) 的选项卡,您可以看到控制台中显示的输出。状态更新时调用相应的函数。
反应状态更新
注:本文由VeryToolz翻译自 Explain lifecycle of ReactJS due to all call to this.setState() function ,非经特殊声明,文中代码和图片版权归原作者 namankedia所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。