组件更新的优化
开发当中存在这样的场景比如,我已经得到的一个组件中渲染了,另一个组件渲染后,前一个组件也会随着更新,这个势必会影响性能,React提供了shouldComponentUpdate(nextProps, nextState)来解决这类问题
基本语法:
shouldComponentUpdate(nextProps, nextState) {
return true;
}
常见使用方式:
shouldComponentUpdate(nextProps, nextState) {
//判断是否绑定的数据发生变化 变化则更新
if (this.props.param !== nextProps) {
return true;
}
return false;
}
需要注意的是修改state或props的时候,不要通过第三个对象来修改,因为shouldComponentUpdate比较的是this.props的引用,所以如果通过第三个对象修改值,但是this.props的引用并没有发生值的变化。
避免直接修改props或state
即不能获取state的值的引用然后进行修改,再使用setState方法进行修改。
例如:
handleClick() {
let words = this.state.words;
words.push('aaa');
this.setState({words: words});
}
上面这个写法明显错误!
正确的写法:
handleClick() {
this.setState(state => ({
words: state.words.concat(['hihi'])
}))
}
或者使用ES6的展开运算符进行数组的连接:
handleClick() {
this.setState(state => ({
words: [...state.words, 'hihi']
}))
}
值得一提的是React中提出Immutable.js,它通过结果共享提供了不可变、持久化集合:
- 不可变:一旦创建,一个集合便不能再被修改。
- 持久化:对集合进行修改,会创建一个新的集合。之前的集合仍然有效。
- 结构共享:新的集合会尽可能复用之前集合的结构,以最小化拷贝操作来提高性能。
基本使用:
const RecordItem = Immutable.Record({foo: null});
const a = new RecordItem({name: 'wjc'})
const b = a.set('name', 'wjc');
const c = b.set('name', 'cj');
console.log(a === b); //true
console.log(a === c); //false
Render Props
在React中Render Props指组件间使用一个值为函数的prop共享的技术。
基本语法:
<Father render={data => (
<h1>Hello {data.target}</h1>
)}/>
即在具有render prop的组件接受一个函数,该函数返回一个React元素(组件),并渲染它。
需要注意的是使用render props的组件必须在该组件的模板中声明需要render的数据
例如:
{this.props.render(this.state.param)}
//然后才可以正常使用render props
使用Render Props的优点:
开发中存在这样的场景,当两个组件(父子)需要共享数据,并且子组件是根据父组件的数据变化,更新组件,而此时,更新整个组件树(父子)显然是非常浪费性能的。所以Render Props则解决了这种场景的问题,让父组件中动态的返回子组件,避免更新整个组件树,而是调整子组件的数据变化。
PropTypes类型检查
类型检查的方式有很多种,在React官方文档中就推荐了两种类型检查的方式,其中一种就是使用JavaScript扩展来进行类型的检查,例如:Flow、TypeScript等。另一种则是React内置的功能PropTypes。
基本语法:
//引入PropTypes
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
//使用ProTypes限制传入的name的数据类型为string
Greeting.propTypes = {
name: PropTypes.string
}
需要注意的是React中的PropTypes也可以设置默认值以及传递的元素的个数,具体可以看官方文档
如果你和我同样是一个young coder!
欢迎关注本人公众号Code center——春繁秋实,年年常茂。
