React组件的生命周期可以分为三个状态:
1.Mounting: 已插入真实 DOM
2.Updating: 正在被重新渲染
3.Unmounting: 已移出真实 DOM
生命周期的方法分别有:
1. componentWillMount:在渲染前调用,即在客户端也在服务端。
2. componentDidMount:组件第一次渲染完成,此时DOM 节点已经生成,可以在这里调用ajax请求,返回数据setState后组件会重新渲染
3. componentWillReceiveProps:在组件接收到一个新的prop时被调用,在接受父组件改变后的props需要重新渲染组件时用的比较多。
4. shouldComponentUpdate:返回一个布尔值,唯一用于控制组件重新渲染的生命周期,在组件接收到新的props或者state时被调用。在初始化或者使用forceUpdate时不会被调用。
5. componentWillUpdate:在组件接收到新的props或者state但是还没有render时被调用,在初始化时不会被调用。
6. componentDidUpdate:在组件完成更新后立即调用,在初始化时被会被调用。组件更新完毕后,react只会在第一次初始化成功后进入componentDidMount之后每次重新渲染后都会进入这个生命周期。
7. componentWillUnmount:在组件从DOM中移除之前立刻被调用。
如下实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 实例</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<script type="text/babel">
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {opacity: 1.0};
}
componentDidMount() {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
}
render () {
return (
<div style={{opacity: this.state.opacity}}>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<Hello name="world"/>,
document.body
);
</script>
</body>
</html>
上面实例Hello组件在加载以后,通过componentDidMount方法设置一个定时器,每隔100毫米重新设置组件的透明度,然后重新进行渲染。
在componentWillUnMount中有时候会碰到一个warning:
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
大概的原因是因为在组件的ajax请求返回的setState,在销毁组件的时候,请求没有完成。
百度了一下大概解决办法:
componentDidMount() {
this.isMount === true
axios.post().then((res) => {
this.isMount && this.setState({
aaa:res
})
})
}
componentWillUnmount() {
this.isMount === false
}