componentDidMount
时间: 2024-01-03 15:05:25 浏览: 24
componentDidMount is a lifecycle method in React that gets called when a component has mounted (been added to the DOM) and rendered for the first time. It is often used to perform side effects such as fetching data from an API, setting up event listeners or initializing third-party libraries.
Here's an example of how it might be used:
```
class MyComponent extends React.Component {
componentDidMount() {
// fetch data from an API
fetch('https://myapi.com/data')
.then(response => response.json())
.then(data => {
// set the data in state
this.setState({ data: data });
});
}
render() {
return (
<div>
{/* render the data */}
{this.state.data}
</div>
);
}
}
```
In this example, the componentDidMount method is used to fetch data from an API and set it in the component's state. Once the data is set, it can be rendered in the component's render method.