0、生命周期函数
React生命周期分为挂载、更新、卸载、错误处理四个阶段(不一定全部执行,比如挂载后立刻卸载)。
不同阶段的函数执行过程为:
一、挂载阶段
1、constructor() —— 组件被挂载到DOM之前
这是第一个被调用的方法,用于初始化state和绑定事件处理程序
const MyComponent extends React.Component {
constructor(props){
super(props);
this.state = {
list: []
}
this.handleList = this.handleList.bind(this);
}
}
2、static getDerivedStateFromProps() —— 组件被挂载到DOM之前
这个方法允许组件基于 props 的变更来更新其内部状态。以这种方式获得的组件状态被称为派生状态。
根据经验,应该谨慎使用派生状态,因为如果你不确定自己在做什么,很可能会向应用程序引入潜在的错误。
3、render()
渲染DOM中的元素,返回JSX(纯字符串 / 数字 / null)
⚠️不要在render中setState或与外部API发生交互。
4、componentDidMount() —— 在调用render后,组件被挂载到DOM,并调用该方法
所以在该方法中可以获取DOM元素,于是这个函数可以进行:
4-1)在组件挂载后立即从组件树中获取DOM节点;
4-2)在组件挂载后立即发出网络请求;
4-3)设置订阅、计时器等(取消订阅在componentWillUnmount中介绍)。
二、更新阶段
当修改state或props时,组件会被重新渲染。
1、static getDerivedStateFromProps()
2、shouldComponentUpdate()
在调用 static getDerivedStateFromProps 方法之后,接下来会调用 nextComponentUpdate 方法。
默认情况下,或者在大多数情况下,在 state 或 props 发生变更时会重新渲染组件。不过,你也可以控制这种行为。
你可以在这个方法中返回一个布尔值——true 或 false,用于控制是否重新渲染组件。
这个生命周期方法主要用于优化性能。不过,如果 state 和 props 没有发生变更,不希望组件重新渲染,你也可以使用内置的 PureComponent。(???)
3、render()
4、getSnapshotBeforeUpdate()
1、创建Component方式
1)Function Components:
function Greeting({ message }) {
return <h1>{ `Hello, ${message}! ` }</h1>
}
2)Class Components:
class Greeting extends React.Component {
render(){
return <h1>{ `Hello ${this.props.message}` }</h1>
}
}
⚠️当组件需要state/lifecircle时使用class组件,否则使用function组件
2、PureComponent ?
React.PureComponent is exactly the same as React.Component except that it handles the
shouldComponentUpdate()
method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
3、setState的回调函数
setState回调函数在state更新完并且组件re-render完触发。
⚠️与setState回调函数相比,更推荐使用生命周期函数。( ? )
4、HTML与React事件处理差异
1)事件命名:
html - lowercase:<button onclick='activateLasers()'>
react - camelcase:<button onClick={activateLaser}>
2)取消默认事件:
html - return false:<a href="www.baidu.com" onclick="console.log('clicked me'); return false;">
react - event.preventDefault:
function handleClick(event){
event.preventDefault();
console.log("clicked me");
}