您的位置:首页 > Web前端 > React

react组件的生命周期

2017-05-11 15:42 477 查看
组件的生命周期分成三个状态:

1. Mounting: 已插入真实DOM;

2. Updating: 正在被重新渲染;

3. Unmounting: 已移出真实DOM

React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did函数在进入状态之后调用,三种状态共计五种处理函数。

1) componentWillMount();

2) componentDidMount();

3) componentWillUpdate(object nextProps, object nextState);

4) componentDidUpdate(object prevProps, object prevState);

5) componentWillUnmount()

此外,React还提供两种特殊状态的处理函数

1) componentWillReceiveProps(object nextProps) : 已加载组件收到新参数时调用

2) shouldComponentUpdate(object nextProps, object nextState) : 组件判断是否重新渲染时调用

AJAX

var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},

componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
if (this.isMounted()) {
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}
}.bind(this));
},

render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});

ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.body
);


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: