React componentDidMount() 方法

React 组件生命周期 React 组件生命周期

componentDidMount() 方法格式如下:

componentDidMount()

componentDidMount() 方法在组件挂载后(插入 DOM 树中)立即调用。

依赖于 DOM 节点的初始化应该放在 componentDidMount() 方法中。

以下实例会先输出 muban99,然后使用 componentDidMount() 方法设置在组件挂载后输出 google

实例

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "muban99"}; } componentDidMount() { setTimeout(() => { this.setState({favoritesite: "google"}) }, 1000) } render() { return ( <h1>我喜欢的网站是 {this.state.favoritesite}</h1> ); } } ReactDOM.render(<Header />, document.getElementById('root'));

尝试一下 »

React 组件生命周期 React 组件生命周期