ReactJS – componentDidMount 方法
本文将介绍当组件加载到 DOM 树时如何执行函数。
此方法主要用于 React 生命周期中的加载阶段,用于处理所有网络请求或设置应用程序的所有主要订阅。
你可以在 componentDidMount 方法中随时设置网络请求或订阅,但是为了避免任何性能问题,需要在 React 生命周期卸载阶段调用的 componentWillUnmount 方法中取消订阅这些请求。
语法
componentDidMount()
示例
在本例中,我们将构建一个变色 React 应用程序,它将在组件加载到 DOM 树后立即更改文本颜色。
以下示例中的第一个组件是 App。此组件是 ChangeName 组件的父组件。我们单独创建 ChangeName,并在 App 组件的 JSX 树中将其添加到内部。因此,仅需要导出 App 组件。
App.jsx
import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>Tutorialspoint</h1> <ChangeName /> </div> ); } } class ChangeName extends React.Component { constructor(props) { super(props); this.state = { color: 'lightgreen' }; } componentDidMount() { // Changing the state after 3 sec setTimeout(() => { this.setState({ color: 'wheat' }); }, 2000); } render() { console.log('ChangeName component is called'); return ( <div> <h1>Simply Easy Learning</h1> </div> ); } } export default App;
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
将会产生以下结果。
广告