react 和 seamless-immutable
? 在 react 中,默认改变组件状态或者属性,是会整个组件全部重新渲染,但是 如果只是修改一个地方,而全部渲染,就会浪费资源,大项目中会造成性能问题 ? shouldComponentUpdate
? ? ? ?shouldComponentUpdate?在 react生命周期中就是控制是否重新渲染组件的方法,而该方法默认返回true,这意味着就算没有改变组件的props或者state,也会导致组件的重绘。这就经常导致组件因为不相关数据的改变导致重绘,这极大的降低了React的渲染效率,这个问题,可以测试出来的 ? ? ? PureComponent 和 Component 的区别 ? ? ?React.PureComponent 与 React.Component 几乎完全相同,但 React.PureComponent 会自动通过props和state的浅对比来控制是否重新渲染组件 ? ?如果在? PureComponent 组件中,重写了 shouldComponentUpdate 方法 会根据 shouldComponentUpdate方法返回值判断是否重新渲染 ? ? PureComponent 优缺点 ? ? ?优点: 不需要开发者自己实现shouldComponentUpdate,就可以进行简单的判断来提升性能。 缺点:可能会因深层的数据不一致而产生错误的否定判断,从而shouldComponentUpdate结果返回false,界面得不到更新。 ? ? ?例如: ? ? ? ? ?在父组件中,给子组件 传一个数组对象 var data = [{name:‘zs‘,age: 23},{name:‘ls‘,age: 26}],子组件用这个data 去渲染数据, ? 然后在父组件中 修改data,例如 data[0].age = 1,data.push({name:‘ww‘,age: 30}),这一系列操作,在 PureComponent 下,子组 件是不会更新的,但是我们的数据却是更改了,这就是它的弊端,在简单数据类型是可以的,引用类型数据的比较,会出现问题。 ? ? 这个时候要优化渲染 就要用到 seamless-immutable ? 具体看这2个网站 ? ? https://www.npmjs.com/package/seamless-immutable https://segmentfault.com/a/1190000010438089 ? ? 这里记录下部分 使用api // 一下2种方式 功能是相同的,把js 的数据类型转化成 不可改变的数据类型 Immutable.from([1,2,3]); let arr = Immutable([1,3]); // 转成可修改的数据,才可以修改数据 let data = Immutable.asMutable(arr) // 数组 data.push(5) //添加元素 data[0] = {name: "we",age: 10} // 对象 // 对象赋值 var obj = {}; let newObj = Immutable.setIn(obj,[‘key‘],data) var obj = {}; let newObj = obj.setIn([‘key‘],data) ? shouldComponentUpdate 方法 配合??seamless-immutable 使用,就可以控制复杂复杂数据类型的更新渲染了 ? 父组件: import React,{ Component } from ‘react‘; import { connect } from ‘dva‘; import Immutable from ‘seamless-immutable‘; import styles from ‘./IndexPage.css‘; import Example from "../components/Example.js" class IndexPage extends Component{ constructor(props){ super(props) this.state = { flg: true,arr: Immutable.from([{name:‘zs‘,age: 23},{name:‘ls‘,age: 26}]) } } // handClick = () => { let { flg} = this.state this.setState({ flg: !flg }) } handClick1 = () => { const {arr} = this.state; 子组件: import React,{ Component } from ‘react‘; class Example extends Component{ constructor(props){ super(props) this.state = { } } shouldComponentUpdate(nextProps,nextState){ if (this.props.data == nextProps.data) { return false } return true } render(){ const { data } = this.props return( <div> { data.map((item,i)=> <div key={i}> <span>{item.name}</span> <span>{item.age}</span> </div> ) } </div> ) } } Example.propTypes = { }; export default Example; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |