1、React.PureComponent 与 React.Component 的区别
React.PureComponent 与 React.Component 几乎完全相同,但 React.PureComponent 通过 prop 和 state 的 **浅比照 **来实现 shouldComponentUpate()
React.Component:
class A extends React.Component{ //xxx}React.PureComponent:
class B extends React.PureComponent{ //xxx}注意:假如 props 和 state 包含复杂的数据结构,React.PureComponent 可能会因深层数据不一致而产生错误的否定判断,即 state、props 深层的数据已经改变,但是视图没有升级。
image
2、shouldComponentUpate() 的机制
只需 state、props 的状态发生改变,就会 re-render,即便 state、props 的值和之前一样
有三种办法优化 shouldComponentUpate 生命周期
(1)只用简单的 props 和 state 时,考虑 PureComponent (理由如 第 1 点)
(2)当开发者知道 深层的数据结构 已经发生改变时使用 forceUpate()
(3)使用 不可变对象(如 Immutable.js) 来促进嵌套数据的快速比较
image
3、React 强制升级状态之 forceUpdate()
我们都知道,当 state、props 状态改变时,React 会重渲染组件。
但假如你不用 props、state,而是其余数据,并且在该数据变化时,需要升级组件的话,即可以调用 forceUpdate(),来强制渲染
举个例子:
class A extends Component { this.a=1 Add(){ this.a+=1 this.forceUpdate() } //调用Add() ...}流程:当调用 forceUpdate() 方法后
image
注意:
(1)假如改变标签的话,React 仅会升级 DOM。
(2)render() 函数中最好从 this.props 和 this.state 读取数据,forceUpdate() 仅在“宝贵”的时刻用。
4、服务端渲染
ReactDOM.render() 将在 React.v17废弃,改成 ReactDOM.hydrate()
5、ReactDOM.unmountComponentAtNode(container)
这个方法会从 DOM 中删除已经挂载的 React component 并且清除上面 注册的事件 和 状态,假如 container 中没有挂载 component,则调用此函数不执行任何操作。
返回 true 或者 false
6、babel-plugin-transform-remove-console
在打包React项目后,清理所有 console.log() 语句
image
7、antd 的 Modal 去掉 onCancel 后,点击遮罩层或者右上角叉,不会关闭 模态框
<Modal title={""} visible={this.state.isible} //不能注释掉 onCancel onCancel={this.handleCancel}></Modal>8、利用 ref 实现 <div> 滚动到最下方
class A extends Component { constructor(props){ //xxx this.aa = React.createRef(); } render() { if(this.aa&&this.aa.current){ this.aa.current.scrollTop = this.aa.current.scrollHeight } return ( <div style={{height:'330px',border:'1px red solid',overflow: 'auto'}} ref={this.aa} > //100个肯定高度的div </div> )}}
image
9、ESLint Unexpected use of isNaN:错误使用 isNaN
// badisNaN('1.2'); // falseisNaN('1.2.3'); // true// goodNumber.isNaN('1.2.3'); // falseNumber.isNaN(Number('1.2.3')); // true10、Assignment to property of function parameter ‘item’ :循环时,不能增加/删除对象属性
let obj=[{a:1,b:2},{c:3,d:4}]//badobj.map((item, index) => { //增加Index属性 item.index = index + 1; });//goodcolumnsData.forEach((item, index) => { // 增加序号 item.index = index + 1; });
image
11、error Use array destructuring:使用数组结构来赋值
//badnewTime = array[0];//good[newTime] = array;12、error Use object destructuring:使用对象结构来赋值
//badconst clientWidth = document.body.clientWidth;//goodconst {body:{clientWidth}} = document;13、Require Radix Parameter (radix):缺少参数
//badparseInt(numberOne);//goodparseInt(numberOne,10);14、禁止浏览器双击选中文字
.aa{ //浏览器双击选不到文字 -webkit-user-select: none;}
image
假如您对这个文章有任何异议,那么请在文章评论处写上你的评论。
假如您觉得这个文章有意思,那么请分享并转发,或者者也可以关注一下表示您对我们文章的认可与鼓励。
愿大家都能在编程这条路,越走越远。