componentWillUpdate生命周期在shouldComponentUpdate返回true后被触发。在这两个生命周期只要视图更新就会触发,因此不能再这两个生命周期中使用setState。否则会导致死循环
在shouldComponentUpdate 这个方法中,这个方法主要用来判断是否需要调用render方法重绘DOM
因为DOM的描绘非常消耗性能,如果能够在shouldComponentUpdate方法中能写出更优化的 diff算法,极大的提高性能
类组件中的优化手段
PureComponent 作为基类。React.memo 高阶函数包装组件。shouldComponentUpdate 生命周期函数来自定义渲染逻辑。方法组件中的优化手段
useMemo。useCallBack。其他方式
Suspense 和 lazy 进行懒加载,例如:import React, {
lazy, Suspense } from "react";
export default class CallingLazyComponents extends React.Component {
render() {
var ComponentToLazyLoad = null;
if (this.props.name == "Mayank") {
ComponentToLazyLoad = lazy(() => import("./mayankComponent"));
} else if (this.props.name == "Anshul") {
ComponentToLazyLoad = lazy(() => import("./anshulComponent"));
}
return (
<div>
<h1>This is the Base User: {
this.state.name}</h1>
<Suspense fallback={
<div>Loading...</div>}>
<ComponentToLazyLoad />
</Suspense>
</div>
)
}
}
componentWillMount:在渲染之前执行,用于根组件中的 App 级配置。
componentDidMount:在第一次渲染之后执行,可以在这里做AJAX请求,DOM 的操作或状态更新以及设置事件监听器。
componentWillReceiveProps:在初始化render的时候不会执行,它会在组件接受到新的状态(Props)时被触发,一般用于父组件状态更新时子组件的重新渲染
shouldComponentUpdate:确定是否更新组件。默认情况下,它返回true。如果确定在 state 或 props 更新后组件不需要在重新渲染,则可以返回false,这是一个提高性能的方法。
componentWillUpdate:在shouldComponentUpdate返回 true 确定要更新组件之前件之前执行。
componentDidUpdate:它主要用于更新DOM以响应props或state更改。
componentWillUnmount:它用于取消任何的网络请求,或删除与组件关联的所有事件监听器。
在 React中,组件负责控制和管理自己的状态。
如果将HTML中的表单元素( input、 select、 textarea等)添加到组件中,当用户与表单发生交互时,就涉及表单数据存储问题。根据表单数据的存储位置,将组件分成约東性组件和非约東性组件。
约束性组件( controlled component)就是由 React控制的组件,也就是说,表单元素的数据存储在组件内部的状态中,表单到底呈现什么由组件决定。
如下所示, username没有存储在DOM元素内,而是存储在组件的状态中。每次要更新 username时,就要调用 setState更新状态;每次要获取 username的值,就要获取组件状态值。
class App extends Component {
//初始化状态
constructor(props) {
super(props);
this.state = {
username: "有课前端网",
};
}
//查看结果
showResult() {
//获取数据就是获取状态值
console.log(this.state.username);
}
changeUsername(e) {
//原生方法获取
var value = e.target.value;
//更新前,可以进行脏值检测
//更新状态
this.setState({
username: value,
});
}
//渲染组件
render() {
//返回虚拟DOM
return (
<div>
<p>
{
/*输入框绑定va1ue*/}
<input type="text" onChange