当组件已经放置在DOM(文档对象模型)中时,componentDidMount()方法允许我们执行React代码。在React Life-cycle的安装阶段(即渲染组件之后)调用此方法。
所有AJAX请求以及DOM或状态更新都应在componentDidMount()方法块中进行编码。我们也可以在此处设置所有主要的订阅,但是为了避免任何性能问题,请始终记住使用componentWillUnmount()方法取消订阅。
用法:
componentDidMount()
创建React应用程序:
步骤1:使用以下命令创建React应用程序:
npx create-react-app functiondemo
第2步:创建项目文件夹(即functiondemo)后,使用以下命令将其移至该文件夹:
cd functiondemo
项目结构:如下图所示。

项目结构
例:在此示例中,我们将构建一个名称颜色应用程序,当在DOM树中呈现组件时,该应用程序将更改文本的颜色。
App.js:现在在App.js文件中写下以下代码。在这里,App是我们编写代码的默认组件。
Javascript
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
// Initializing the state
this.state = { color:'lightgreen' };
}
componentDidMount() {
// Changing the state after 2 sec
// from the time when the component
// is rendered
setTimeout(() => {
this.setState({ color:'wheat' });
}, 2000);
}
render() {
return (
<div>
<p
style={{
color:this.state.color,
backgroundColor:'rgba(0,0,0,0.88)',
textAlign:'center',
paddingTop:20,
width:400,
height:80,
margin:'auto'
}}
>
GeeksForGeeks
</p>
</div>
);
}
}
export default App;
运行应用程序的步骤:从项目的根目录中使用以下命令运行应用程序:
npm start
输出:
相关用法
- ReactJS shouldComponentUpdate()用法及代码示例
- ReactJS getSnapshotBeforeUpdate()用法及代码示例
- ReactJS bind()用法及代码示例
- ReactJS componentDidUpdate()用法及代码示例
- ReactJS componentDidCatch()用法及代码示例
- ReactJS getDerivedStateFromError()用法及代码示例
- ReactJS componentWillUnmount()用法及代码示例
注:本文由纯净天空筛选整理自rbbansal大神的英文原创作品 ReactJS componentDidMount() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。