最近在学习 React,希望通过几篇文章对知识进行梳理( react组件的生命周期、react组件的最佳实践、react+redux 状态管理实践、以及 Fiber对react带来的变革)
任何一个应用程序都会有自己的完整生命周期。只有了解生命周期才有可能写出性能更好更健壮的应用程序。当然对比后端,前端对生命周期的定义理解使用场景还是有很大区别。
React V16.3 对开发工具进行了更新,引入了StrictMode
,与AsyncMode
的严格模式组件来引导你遵循最佳实践。同时也推出了Context API 让 React 拥有安全稳定的 global store。另一重大改进就是组件生命周期,本文将对React的生命周期进行梳理。
# 一 组件 component
在React中一切皆组件,编写组件有两种方式:定义为类或则函数
## 1 定义类 extends class
拥有props 和 state 属性,同时也拥有生命周期函数。大部分情况下推荐使 PureComponent方式,它比 component 拥有更好的性能。
React.createClass:用ES5实现,就只能用 createClass
var React = require("react");
var Greeting = React.createClass({
propTypes: {
name: React.PropTypes.string //属性校验
},
getDefaultProps: function() {
return {
name: 'Mary' //默认属性值
};
},
getInitialState: function() {
return {
count: this.props.initialCount}; //初始化state
},
handleClick: function() {
//用户点击事件的处理函数
},
render: function() {
return <h1>Hello, {
this.props.name}</h1>;
}
});
module.exports = Greeting;
React.Component:基于ES6 对类和继承的支持
import React from 'react'
class Greeting extends React.Component {
constructor(props) {
super(props);
this.state = {
count: props.initialCount};
this.handleClick = this.handleClick.bind(this);
}
//static defaultProps = {
// name: 'Mary' //定义defaultprops的另一种方式
//}
//static propTypes = {
//name: React.PropTypes.string
//}
handleClick() {
//点击事件的处理函数
}
render() {
return <h1>Hello, {
this.props.name}</h1>;
}
}
Greeting.propTypes = {
name: React.PropTypes.string
};
Greeting.defaultProps = {
name: 'Mary'
};
export default Greating;
React.PureComponent:为了避免组件进行不必要的重新渲染,我们通过定义shouldComponentUpdate 来优化性能,由于这种场景非常常见,React 官方在 V15.3 中提供了PureComponent 类。但 PureComponent 只做了浅比较(shallowEqual),所以使用前需要深入了解其用法。
可以参考:https://juejin.im/entry/5934c9bc570c35005b556e1a
import React from 'react'
class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: 1};
}
render() {
return (
<button
color={
this.props.color}
onClick={() => this.setState(state => ({
count: state.count + 1}))}>
Count: {
this.state.count}
</button>
);
}
}
## 2 无状态功能组件 (Stateless Functional Component)
不需要内部状态 state,也不需要有生命周期函数,只需要接收 props 属性。一般用于展示类组件。
import React from 'react';
const Button = ({
day,
increment
}) => {
return (
<div>
<button onClick={
increment}>Today is {
day}</button>
</div>
)
}
Button.propTypes = {
day: PropTypes.string.isRequired,
increment: PropTypes.func.isRequired,
}
参考:谈一谈创建React Component的几种方式
# 二 V16.3 对生命周期函数的变更
React16.3开始,组件的生命周期发生了重要的变化
【有三个 API 被舍弃】
- componentWillMount()
- componentWillReceiveProps(nextProps)
- componentWillUpdate(nextProps, nextState)
【被舍弃的 API 现阶段都以 UNSAFE_
前缀开头,将会在下一个主版本 V17 中完全删除】
- UNSAF